改变组件之间的状态模式

Change state mode between components

我有以下 3 个组件:SectionBox(父级)、SectionData 和 Section(子级)。通过以下代码,我尝试在这三个组件之间共享数据,这样当我单击 Section 组件中的按钮时,我可以看到 SectionData 组件中的变化。 我尝试使用我在此处看到的一些示例来这样做,方法是使用 'state' 对象并将函数作为参数传递,但它不起作用。 这是我的代码:

*

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>
        );
    }
}

你打错了,不是 "onclick",是 "onClick"。

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

应该是

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