首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReactJS,相同组件,从其他组件onClick中拔出类

ReactJS,相同组件,从其他组件onClick中拔出类
EN

Stack Overflow用户
提问于 2016-06-12 13:25:44
回答 1查看 638关注 0票数 0

所以我有一个Main.jsx父文件,它接受两个相同的组件,但是附加了不同的数据。子组件有一个带有onClick的按钮。

Main.jsx

代码语言:javascript
复制
    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

代码语言:javascript
复制
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文件中尝试了以下内容,但这似乎不起作用,据我所读,最好还是让大多数组件保持无状态状态:

代码语言:javascript
复制
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'})
       }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-12 13:48:10

这应该在父级处理。父母可以使一个是sm-8,另一个是sm-4。

代码语言:javascript
复制
<button onClick={this.props.togglePane} />

在父级中,处理它

代码语言:javascript
复制
<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' });
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37774796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档