javascript - 将状态从 childComp 传输到 ParentComp

标签 javascript reactjs redux

我有两个组件,我需要将state从子组件传输到父组件

class Parent Component {
   this.state = {text: hahaha}
   this.props.action(text, data)

   <Children Component />
   <button onClick={this.props.action(text, data)}
}

class Children Component {
   this.state = {date: 12.12.12}
}

另一个小技巧是我在父组件中有redux-action,它需要两个参数文本和日期,总之,当我单击按钮时我需要传输statechildCompparentComp,然后在 parentComp 中创建具有两个参数的操作。那么我怎样才能做到这一点呢?

最佳答案

Refer component communication

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            content: 'initial'
        }
        this.updateParentState = this.updateParentState.bind(this);
    }

    updateParentState(content){
        this.setState({
            content: content
        })
    }

    render(){
        let { content } = this.state;
        return <div>
            <Child updateParentState={this.updateParentState}/>
            <h1>{ content }</h1>
        </div>
    }
}

class Child extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            value: 'initial'
        }
        this.handleParentState = this.handleParentState.bind(this);
        this.changeContent = this.changeContent.bind(this);
    }

    handleParentState(content){
        let { updateParentState } = this.props;
        let { value } = this.state;
        updateParentState(content);
    }

    changeContent(event){
        this.setState({
            value: event.target.value
        })
    }

    render(){
        let { value } = this.state
        return <div>
            <input value={value} onChange={this.changeContent}/>
            <button onClick={this.handleParentState}>Update Parent State</button>
        </div>
    }
}

关于javascript - 将状态从 childComp 传输到 ParentComp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869155/

相关文章:

javascript - 想要将所有导航选项卡收集到页面缩放上的图标中

reactjs - 如何设计 Redux 存储和操作?

javascript - 带有嵌套对象数组的 Normalizr

javascript - 访问发送到组件的 props 以及 Redux 状态数据

javascript - 用于身份验证 token 的 Angular $http 拦截器

javascript - 如何为工作海报 REST 调用定义 MFP javascript 适配器?

javascript - 拉斐尔 JS 问题

node.js - MERN 教程问题 : Cannot read properties of undefined (reading 'collection' )

javascript - 单击按钮时使文本字段可编辑

javascript - React-Bootstrap 未捕获引用错误 : require is not defined