📌  相关文章
📜  从子反应更新父状态 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:55.307000             🧑  作者: Mango

代码示例1
class Parent extends React.Component {
    constructor(props) {
        super(props)

        // Bind the this context to the handler function
        this.handler = this.handler.bind(this);

        // Set some state
        this.state = {
            messageShown: false
        };
    }

    // This method will be sent to the child component
    handler(id) {
        this.setState({
            messageShown: true,
            id: id
        });
    }

    // Render the child component and set the action property with the handler as value
    render() {
        console.log(this.state);
        return (
           
{this.state.id}
); } } class Child extends React.Component { render() { return (
{/* The button will execute the handler function set by the parent component */}
) } } ReactDOM.render(, document.getElementById('main'));