小编典典

将值从子级传递到父级组件

reactjs

我有两个组成部分:

  • 第一个是父组件,它是通常的React组件。
  • 第二个是孩子,它是功能组件。

我想将 Titles 的值(处于子状态)传递给父Component。这是我的 子组件 代码:

        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} />
         }

这看起来很容易,但这是我第一次使用功能组件。你能帮我吗 ?


阅读 189

收藏
2020-07-22

共1个答案

小编典典

React就是关于在组件树中向下流动的数据。如果您希望Child能够显示和/或修改彼此之间的共享状态ChildParent则应提升状态并将其向下传递propschildren

const Parent = () =>{
    const [title, settitle] = useState('foo')

    return <Child title={title} setTitle={setTitle} />
}


const Child = ({ title, setTitle}) =>{
     return <input value={title} onChange={e => setTitle(e.target.value)} />
}

基于课堂的组件

class Parent extends React.Component{
    state = { title: '' }

    setTitle = title => this.setState({ title })

    render(){
        const { title } = this.state
        return <Child title={title} setTitle={this.setTitle} />
    }
}


class Child extends React.Component{
    render(){
        const { title, setTitle } = this.props
        return <input value={value} setTitle={e => setTitle(e.target.value)} />
    }
}
2020-07-22