问题是我不能访问actuve的值或更改它? 这是因为道具是不可变的吗? 如果是,我应该为每个EventInLife元素/组件创建一个单独的变量吗?
null
import React from 'react';
import styled,{ css } from 'styled-components';
const EventInLife = (props) => {
/*
adds the active theme to each element(example: if active then the styles
would be barbar and barbaractive if not they would be barbar and barbar)
*/
return (
<div className={`barbar barbar${ props.actuve }`}>
<div className={`square square${ props.actuve }`}></div>
<div className={`heading heading${ props.actuve }`}>{props.heading}</div>
<div className={`date date${ props.actuve }`}>{props.date}</div>
</div>
);
}
function App() {
//Manages which value is active
var lastactive=0;
function bruh(t,n){
document.getElementsByName(t)[lastactive].actuve='';
document.getElementsByName(t)[n].actuve = 'active';
lastactive=n;
}
return(
<EventInLife heading={'Top'} date={'145'} actuve={'active'} onClick={()=>bruh('EventInLife',0)}/>
<EventInLife heading={'trop'} date={'456456'} actuve={''} onClick={()=>bruh('EventInLife',1)}/>
<EventInLife heading={'brop'} date={'45646'} actuve={''} onClick={()=>bruh('EventInLife',2)}/>
<EventInLife heading={'crop'} date={'45646'} actuve={''} onClick={()=>bruh('EventInLife',3)}/>
<EventInLife heading={'wrop'} date={'145645'} actuve={''} onClick={()=>bruh('EventInLife',4)}/>
);
}
/*the css style names (i made them only overide what they needed to)*/
.barbar{}
.barbaractive{}
.squareactive{}
.squareactive{}
.headingactive{}
.headingactive{}
.dateactive{}
.dateactive{}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
null
是的,道具是不可变的,把它们看作是传递给函数的参数。 任何将在组件生命周期中改变的值都应该存储在组件的状态中,改变状态将导致组件重新跟踪,从而在DOM上显示改变,如果状态被正确利用的话。 下面是一个简单的例子,其中每个组件都有一个按钮,该按钮触发激活状态的切换,从而触发组件的重新滚动,这导致重新计算类变量,从而更改传递给div元素的类名。 我假设每个元素最初都是假的。
import React , {useState} from 'react';
const RandComponent = (props) => {
const [isActive , setIsActive] = useState(false);
const classes = isActive ? 'bar barActive' : 'bar';
return(
<>
<div className={classes}>hi</div>
<button onClick={() => setIsActive(!isActive)}>{isActive ? 'make me inactive' : 'make me active'}</button>
</>
);
}