我有两个组件:
我想将Titles的值(处于子状态)传递给父组件。这是我的子组件代码:
export default function ChildApp(props) { const [titles,setTitles] = React.useState("") return ( <Button title="submit" onPress={()=>setTitles("asma")}/> ); }
这是我的父组件:
this.state = { titles:"foo"} setTitles = titles => this.setState({ titles }) // i need the value of Titles to be set in state export default class ParentApp extends Component { const titles = this.state.titles <ChildApp titles={titles} setTitles={this.setTitles} /> }
这看起来很容易,但这是我第一次使用函数式组件。你能帮助我吗?
当然,您可以通过将函数从父组件传递到子组件来实现这一点。子组件可以调用此函数将更新的状态值传回父组件。您可以这样做:
修改您的子组件以接受setTitles作为道具并在按下按钮时调用它。
setTitles
import React from 'react'; export default function ChildApp({ setTitles }) { const [titles, setLocalTitles] = React.useState(""); const handlePress = () => { setLocalTitles("asma"); setTitles("asma"); // Pass the new title to the parent component }; return ( <button onClick={handlePress}>Submit</button> ); }
在父组件中,你可以将setTitles函数作为 prop 传递给子组件。
import React, { Component } from 'react'; import ChildApp from './ChildApp'; export default class ParentApp extends Component { constructor(props) { super(props); this.state = { titles: "foo" }; } setTitles = (titles) => { this.setState({ titles }); }; render() { const { titles } = this.state; return ( <div> <h1>Current Title: {titles}</h1> <ChildApp setTitles={this.setTitles} /> </div> ); } }
ChildApp
setLocalTitles
ParentApp
render
此设置允许子组件更新父组件的状态,从而实现从子组件到父组件的数据流。