【问题标题】:Is there a way of passing props from child to parent without onClick有没有一种方法可以在没有 onClick 的情况下将道具从孩子传递给父母
【发布时间】:2020-05-22 09:58:50
【问题描述】:

我看到了一些示例,这些示例展示了如何使用子组件上的 onClick 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;

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你必须调用父母函数:

    componentDidMount() {
        fetch('https://someapi/getusername', {
    
        })
        .then(function(response) { 
            return response.json() 
        })
        .then((data) => {
            this.props.changeLink(data);
    
        })
    }
    

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

    【讨论】:

    • 没问题,我还记得当我试图弄清楚时我是多么困惑:-D
    【解决方案2】:

    在您的情况下,我认为父母必须进行提取,并将结果作为道具提供给孩子。

    如果你真的需要孩子获取数据,你必须调用回调 changeLink 作为从父母到孩子的道具:

    componentDidMount() {
        fetch('https://someapi/getusername', {
    
        })
        .then(function(response) { 
            return response.json() 
        })
        .then((data) => {
            this.setState(
                { username: data }
            )
            this.props.changeLink(data)
        })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      相关资源
      最近更新 更多