[英]ReactJS Passing state from parent to child
我有以下内容,想知道是否有更优雅的方式将this.state.currentSection
状态传递给<HeaderButton />
?:
...
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>
...
你可以像这样在渲染方法中解构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>
);
}
您可以为此使用单个变量,而不是编写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>)
}
您可以使用 javascript 扩展符号。
render() {
const headerButtonState = {
active:this.state.currentSection === 'SPECIAL',
text:"Special",
count:23,
backgoundColor:'#c04c36'
}
return <div>
<div className="section" style={this.state.currentSection === 'SPECIAL' ? {} : {'opacity': '0.4'}}>
<HeaderButton {...headerButtonState} onClick={this.setActiveSpecial}/>
</div>
}
如果你只想处理一个条件,而不是三元使用&&。
即,而不是:
isActive ? <Component/> : null;
用:
isActive && <Component/>
我会根据该部分的--special
类修饰符修改 css 中所有与样式相关的内容。
import classnames from 'classnames';
...
render() {
const { currentSection } = this.state;
const isSectionSpecial = currentSection === 'SPECIAL';
return (
<div>
<div className={classnames('section', {
'section--special': isSectionSpecial
})}>
<HeaderButton active={isSectionSpecial} />
</div>
</div>
)
}
CSS
.section {
...
}
.section--special {
opacity: 0.4;
}
.header-button {
...
}
.section--special .header-button {
background-color: #c04c36;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.