首页 > 解决方案 > 有没有一种方法可以在没有 onClick 的情况下将道具从孩子传递给父母

问题描述

我已经看到了一些示例,这些示例显示了如何使用子组件上的 onClick on onChange 事件将道具从子组件传递给其父组件,但我正在努力弄清楚如何被动地传递道具。

我想要的是让子组件执行获取操作,然后将响应传递给父组件。

// PARENT component
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            homeLink: 'inital'
        }
    }

    handleNamechange(newName) {
        this.setState({
            homeLink: newName
        })
    }

    render() {

        return(
            <section>
                <h1>{this.state.homeLink}</h1>

                <GetUserComponent 
                    changeLink={this.handleNamechange.bind(this)}
                />

            </section>
        )
    }
}
export default App;

我努力的部分是在没有 onClick 的情况下将道具发送给父级,并在获取完成后传递道具

// CHILD Component
class GetUserComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            homeLink: 'xxxx'
        }
    }

    componentDidMount() {
        fetch('https://someapi/getusername', {

        })
        .then(function(response) { 
            return response.json() 
        })
        .then((data) => {
            this.setState(
                { username: data }
            )
        })
    }

    onChangeLink() {
        this.props.changeLink(this.state.homeLink)
    }

    render() {
        return (
            <div>
                <span onClick={this.onChangeLink.bind(this)}
                    >Change Header Link</span>
            </div>
        )
    }

}

export default GetUserComponent;

我不确定我是否做错了,或者这是否根本无法完成并且您必须使用点击事件,但无论哪种方式都非常感谢您的帮助。

标签: javascriptreactjs

解决方案


你必须调用父母函数:

componentDidMount() {
    fetch('https://someapi/getusername', {

    })
    .then(function(response) { 
        return response.json() 
    })
    .then((data) => {
        this.props.changeLink(data);

    })
}

然后它将执行该handleNamechange函数并更新父状态。


推荐阅读