所以我有一个Main.jsx父文件,它接受两个相同的组件,但是附加了不同的数据。子组件有一个带有onClick的按钮。
Main.jsx
class Main extends React.Component {
render() {
return (
<div className="row">
<Child
styleName="pane-1 text-center"
title="Title 1"
description="Some Text"
/>
<Child
styleName="pane-2 text-center"
title="Title 2"
description="Some Text"
/>
</div>
)
}
}
export default MainChild.jsx
class Child extends React.Component {
render() {
return (
<div className={classnames('pane', this.props.colName)}>
<div className={classnames(this.props.styleName)}>
<div className="col-sm-6 col-sm-offset-3">
<h2>{this.props.title}</h2>
<p>{this.props.description}</p>
<button onClick={this.togglePane} className="btn btn-primary-outline">Tell Me More</button>
</div>
</div>
</div>
)
}
}
export default Child现在,在上面的Child.jsx文件中,需要更改的是colName道具,但只需要对用户单击按钮的组件进行更改。
我也在Child.jsx文件中尝试了以下内容,但这似乎不起作用,据我所读,最好还是让大多数组件保持无状态状态:
constructor(props) {
super(props);
this.state = {
colName: 'col-sm-6'
};
this.togglePane = this.togglePane.bind(this);
}
togglePane() {
if (this.state.colName == 'col-sm-6'){
this.setState({colName: 'col-sm-4'})
} else {
this.setState({colName: 'col-sm-6'})
}
}发布于 2016-06-12 13:48:10
这应该在父级处理。父母可以使一个是sm-8,另一个是sm-4。
<button onClick={this.props.togglePane} />在父级中,处理它
<Child
styleName="pane-1 text-center"
colName={this.state.firstCol}
togglePane={this.togglePane}
/>
<Child
styleName="pane-2 text-center"
colName={this.state.secondCol}
togglePane={this.togglePane}
/>
togglePane() {
if(this.state.firstCol==='col-sm-6') {
this.setState({ firstCol: 'col-sm-8', secondCol: 'col-sm-4' });
} else {
this.setState({ firstCol: 'col-sm-6', secondCol: 'col-sm-6' });
}
}https://stackoverflow.com/questions/37774796
复制相似问题