更改组件之间的状态模式

时间:2016-05-05 09:19:19

标签: reactjs react-jsx

我有以下3个组件:SectionBox(父级),SectionData和Section(子级)。使用以下代码,我尝试在这三个组件之间共享数据,这样当我单击Section组件中的按钮时,我可以看到SectionData组件中的更改。 我尝试用我在这里看到的一些例子,通过玩“状态”来做到这一点。对象并将函数作为参数传递,但它不起作用。 这是我的代码:

*

import React from 'react';
import Section from './Section';
import SectionData from './SectionData';

export default class SectionBox extends React.Component {

    constructor () {
        super();
        this.state = {
          dataToShow: "A"
        };
    }

    render() {
        return (
            <div className="col-md-2">
                <div className="container-fluid">
                    <Section onUpdate={this.changeDataToShowState.bind(this)} title="A"/>
                    <Section onUpdate={this.changeDataToShowState.bind(this)} title="B"/>
                    <Section onUpdate={this.changeDataToShowState.bind(this)} title="C"/>
                </div>
                <SectionData data = {this.state.dataToShow}/>
            </div>

    changeDataToShowState (val) {
        this.setState({dataToShow: val});
    }
}

**

import React from 'react';

export default class Section extends React.Component {
    render() {
        return (
        <div className="row">
            <div className="col-md-12">
                <div className="float-box">
                    <button onclick={this.handleClick.bind(this)}>{this.props.title}</button>
                </div>
            </div>
        </div>
        )
    }

    handleClick() {
        var stateMode = this.props.title;
        this.props.onUpdate(stateMode);
    }
}
import React from 'react';

export default class SectionData extends React.Component {

    render() {
        var result;

        if (this.props.data === "A") {
            result = "A";
        } else {
            result = "B or C";
        }

        return (
             <div className="col-md-10">
                 <div className="float-box-content">
                     <div>{result}</div>
                 </div>
             </div>
        );
    }
}

1 个答案:

答案 0 :(得分:2)

你有一个错字,它不是&#34; onclick&#34;,它&#34; onClick&#34;。

 <button onclick={this.handleClick.bind(this)}>{this.props.title}</button>

应该是

 <button onClick={this.handleClick.bind(this)}>{this.props.title}</button>
相关问题