Javascript 将状态从父级传递到子级
我有以下内容,我想知道是否有更优雅的方式将Javascript 将状态从父级传递到子级,javascript,reactjs,Javascript,Reactjs,我有以下内容,我想知道是否有更优雅的方式将this.state.currentSection状态传递给?: ... render() { return <div> <div className="section" style={this.state.currentSection === 'SPECIAL' ? {} : {'opacity': '0.4'}}> <HeaderButton act
this.state.currentSection
状态传递给
?:
...
render() {
return <div>
<div className="section" style={this.state.currentSection === 'SPECIAL' ? {} : {'opacity': '0.4'}}>
<HeaderButton active={this.state.currentSection === 'SPECIAL'} text="Special" count={23} backgoundColor={'#c04c36'} onClick={this.setActiveSpecial}/>
</div>
...
。。。
render(){
返回
...
您可以像这样在render方法中分解this.state
render() {
const { currentSection } = this.state;
const isActive = (currentSection === 'SPECIAL');
return (
<div className="section" style={isActive ? {} : {'opacity': '0.4'}}>
<HeaderButton active={isActive} text="Special" count={23} backgoundColor={'#c04c36'} onClick={this.setActiveSpecial}/>
</div>
);
}
render(){
const{currentSection}=this.state;
const isActive=(currentSection==‘特殊’);
返回(
);
}
您可以为此使用单个变量,而不是写入this.state.currentSection
2次。Boolean(null)==false
render() {
let value = (this.state.currentSection === "SPECIAL") ? null : {opacity:'0.4'};
return (<div>
<div className="section" style={value}>
<HeaderButton active={Boolean(value)} text="Special" count={23} backgoundColor={'#c04c36'} onClick={this.setActiveSpecial}/>
</div>)
}
render(){
let value=(this.state.currentSection==“特殊”)?null:{opacity:'0.4'};
返回(
)
}
您可以使用javascript
render(){
常数headerButtonState={
活动:this.state.currentSection==“特殊”,
案文:“特别”,
计数:23,
背景颜色:“#c04c36”
}
返回
}
如果您只想处理一个条件,而不是三元,请使用&&
即,而不是:
isActive ? <Component/> : null;
isActive?:空;
使用:
isActive&&
我会根据该部分的--特殊的类修饰符修改css中所有与样式相关的内容
从“classnames”导入类名;
...
render(){
const{currentSection}=this.state;
const isSectionSpecial=currentSection==‘特殊’;
返回(
)
}
CSS
部分{
...
}
.部分-特别{
不透明度:0.4;
}
.标题按钮{
...
}
.section--特殊的.header按钮{
背景色:#c04c36;
}
1.您传递的不是this.state.currentSection
,而是与此变量的比较。2.您所说的优雅是什么意思?您是对的,我的意思是有没有比两个三元if更好的方法?
isActive ? <Component/> : null;
isActive && <Component/>