[英]ReactJS, Same Component, Toggle out class from other component onClick
so I have a Main.jsx parent file, that takes two of the same component, but with different data attached to it. 所以我有一个Main.jsx父文件,该文件包含两个相同的组件,但附加了不同的数据。 The Child component has a button with an onClick.
子组件具有带onClick的按钮。
Main.jsx 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 Main
Child.jsx Child.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
Now, in the above Child.jsx file the colName props is what needs to change, but only for the component that the user clicks the button on. 现在,在上面的Child.jsx文件中,需要更改colName属性,但仅对于用户单击按钮的组件而言。
I tried the following in the Child.jsx file as well, but this does not seem to work, and from what I've read, its better to keep most components stateless as well: 我也在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'})
}
}
This should be handled at the parent. 这应该在父母处处理。 Parent can make one be sm-8 and other be sm-4.
父母可以将其中一个设为sm-8,另一个设为sm-4。
<button onClick={this.props.togglePane} />
In the parent, handle it 在父母那里,处理它
<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' });
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.