【问题标题】:Pass values from children to parent component将值从子组件传递给父组件
【发布时间】:2020-02-04 23:04:02
【问题描述】:

我有两个组件:

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

我想将 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} />
         }

这似乎很容易做到,但这是我第一次使用功能组件。 你能帮帮我吗?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    React 是关于在组件树中向下流动的数据。如果您希望您的Child 能够显示和/或修改ChildParent 之间的共享状态,您应该lift your state up 并通过props 将其传递给children

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

    【讨论】:

    • @Asma Destrucutre props 传递给功能组件是一个很好的模式,正如@Dupocas 在他的回答中所写的那样。所以你必须写props.title 来访问你的数据,你可以输入title
    • 很抱歉,我无法得到它。我应该将我的父组件转换为功能性组件吗?
    • 不需要。这只是在我的例子中。我将更新答案,显示它在基于类的组件中是如何工作的
    • 我现在只是在孩子中得到它,你必须把 props.setTitle(e.target.value) 让它工作。非常感谢
    猜你喜欢
    • 2018-05-01
    • 2017-05-19
    • 2019-08-25
    • 2019-02-17
    • 2020-08-21
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多