React-将值从子组件传递到父组件

时间:2019-10-30 15:45:55

标签: reactjs

使用钩子,如何通过单击子组件内部的按钮将 item.id 从子组件传递到父组件?

父组件:

import React from 'react'
import MyList from '../MyList'

const App = props => {
  return (
    <div className='App'>
      <MyList />
    </div>
  )
}

export default App

子组件:

import React from 'react'
import jsonResponse from '../data'

function MyList (props) {
  const list = jsonResponse.map((item) => {
    return (
      <li className='list-container' key={item.id}>
        <h4>Name: {item.name}</h4>    
        <button className='btn'>More details</button>
      </li>
    )
  })

  return (
    <ul id='container'>
      {list}
    </ul>
  )
}

export default MyList

1 个答案:

答案 0 :(得分:1)

反应全部是有关在组件树中向下流动的数据的。如果您希望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)} />
    }
}

但是,如果您确实坚称Child持有state(反模式),则可以执行以下操作

const Parent = () =>{
    const [childProp, setChildProp] = useState(null)

    return <Child setChildProp={setChildProp} />
}

const Child = ({ setChildProp }) =>{
    return <button onClick={() => setChildProp('foo')}>Change to foo</button>
}