如何在2个组件之间传递参数并在" componentWillMount()"中使用它。 - 我正在使用react-navigation

时间:2017-04-27 23:17:11

标签: reactjs react-native react-navigation

这是我需要的一个例子

// This view should receive the parameter before render()
componentWillMount(){
    fetch(parameterHere)
}

此图片只是上面代码的图片。 image

1 个答案:

答案 0 :(得分:1)

通过将父项组件作为prop从父项传递给子项来传递值。

class ComponentA extends React.Component {
    render() {
        <ComponentB mProp={someValue}/>
    }
}

class ComponentB extends React.Component {
    componentWillMount() {
        fetch(this.props.mProp);
    }

    render() {
        ...
    }
}

通过将该prop提升到共享父组件并在父组件中管理该prop的值来在两个子组件之间传递值

class ParentComponent extends React.Component {
    onChangeMProp = (newValue) => {
        this.setState({ someValue: newValue });
    }

    render() {
        const { someValue } = this.state;

        return (
            <div>
                <ComponentA 
                    onChangeMProp={this.onChangeMProp} 
                    mProp={someValue}
                />
                <ComponentB 
                    onChangeMProp={this.onChangeMProp} 
                    mProp={someValue}
                />
            </div>
        )
    }
}