首页 > 解决方案 > 我想将子组件的项目从子组件设置到父组件

问题描述

我想扩展子组件中的数字,改变父组件的计数状态。如何将子组件中的数字从父组件更改为父组件的计数状态?

例如,我想在父组件按下子组件创建的标记为 12 的按钮时,将父组件的计数状态更新为 12。

父组件

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: ""
        }
    }
    render() {
        return (
            <Child />
        )
    }
}

子组件

class Child extends Component {
    render() {
        const number = ["12", "14", "15", "16", "22", "35", "6", "92", "47", "32", "75", "67"]
        return (
            <div>
                {(() => {
                    const items = [];
                    for (let i = 1; i <= 12; i++) {
                        items.push(<button>{number[i]}</button>)
                    };
                    return <>{items}</>;
                })()}
            </div>
        )
    }
}

标签: reactjs

解决方案


将一个函数从父组件传递给子组件,当单击按钮时,子组件将调用该函数,并在该函数中更新父组件的状态,例如父组件:

class Parent extends Component {
constructor(props) {
    super(props);
    this.state = {
        count: ""
    }
}
render() {
    return (
        <Child onButtonClick={(number) => this.setState({count: this.state.count + number})}/>
    )
}
}

子组件:

class Child extends Component {
render() {
    const number = ["12", "14", "15", "16", "22", "35", "6", "92", "47", "32", "75", "67"]
    return (
        <div>
            {(() => {
                const items = [];
                for (let i = 1; i <= 12; i++) {
                    items.push(<button onClick={() => this.props.onButtonClick(number[i])}>{number[i]}</button>)
                };
                return <>{items}</>;
            })()}
        </div>
    )
}
}

推荐阅读