如何将道具从子组件传递给父组件

时间:2020-12-20 07:51:53

标签: reactjs

如何将道具(修改后)从子组件传递给父组件。

一些细节: 我正在处理一个现有的代码库,其中嵌入了父组件 'unstated.Container' 和一个单独的 Child Component ,我试图在其中添加一个按钮。什么时候 用户单击此按钮会更新某些值,该值需要传递给父级 组件。

谢谢。

 import {Container} from 'unstated';

   class DelContainer extends Container{

     state = { sortAsc : true, notified : null}

    setVal = async (Id, value)  => { console.log (`Id : ${Id});  console.log('value: ${value}); }

}

//Child Component (Separate file)
const ChildItems = (props) => {
  const [some_value ] = props;
  const [some_color, setColor] = useState(" ");

 const MarkIt = ({some_value})
 {
   some_value = this.props.some_value;  //ISSUE HERE
 }

 return (
   <IconButton >
      <StarOutlinedIcon onClick = {MarkIt} style={{color: `${some_color}`}}/>
   </IconButton>
 );
}

//Parent Component (Separate file)
import {Subscribe} from 'unstated';
const DelList = (props) => {

    return(

        <Subscribe to ={[DelContainer]}>
        {
           (delStore) => {
                   const[person, isLoading] = delStore.state;
             return(
                     <div>
                        <List className = {props.className} isLoading = {Loading}>
                        {
                             isLoading && person
                               .map((person, index)=>{
                                 return <ChildItem key={index}
                                           person = {person}
                                           some_value = {delStore.MarkIt(some_value)}; 
                                           
                               }
                        }
                       </List<
                     </div>
                   )
          }
        }
      );
 }

1 个答案:

答案 0 :(得分:0)

阅读: How to update parent's state in React?

Reactjs 文档: https://reactjs.org/docs/lifting-state-up.html

class Parent extends React.Component {

  liftStateHander=()=> {
    this.setState({
       name:"John"
    })
  }

  render() {
    return <Child handler={this.liftStateHander} />
  }
}

class Child extends React.Component {
  render() {
    return (
       <button onClick={this.props.handler}>
          Click For Change State Parent 
       </button>
    )
  }
}