Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

reactjs - Pass values from children to parent component

I have two components :

  • The first one is the parent Component which is a usual React Component.
  • The second one is the child which is a functional component.

I want to pass the value of Titles (in the child state) to the parent Component. Here is my code of Child Component:

        export default function ChildApp(props) {

        const  [titles,setTitles] = React.useState("")

          return (

           <Button title="submit" onPress={()=>setTitles("asma")}/>

               );
             }

And here is my Parent Component :


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

It seems easy to do but it's the first time for me working with functional components. Can you help me please ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

React is all about data flowing down in the components tree. If you want your Child to be able to show and/or modify a shared state between Child and Parent you should lift your state up and pass it down via props to it's 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)} />
}

In class based components

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...