Accessing input value from stateless child component in parent through refs

前端 未结 2 1069
故里飘歌
故里飘歌 2021-01-07 10:48

I\'m creating a program to track store inventory. I have an array of item names (strings) that I map through to generate a component that renders a heading for each item al

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-07 11:39

    You are using a functional component which doesn't have a state or refs. You have two options, Either set the value as props passed down from the parent or make it a stateful component.

    Stateless components must be dumb component used specifically for rendering and all logic must reside in the stateful parent component.

    According to the docs

    You may not use the ref attribute on functional components because they don't have instances.You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state

    In first case

        function Inventory(props){
          let items = ['milk', 'bread', 'butter'],
          itemInput = items.map((val,index) => {
          return(
            

    {val}

    props.handleChange(e, val)}/>
    ) }) return(
    {itemInput}
    ) };

    And then the parent will have the logic like

     
    
    
     handleChange = (e, key) => {
          var childInputVal = {...this.state.childInputVal}
          childInputVal[key] = e.target.value
          this.setState({childInputVal})
     }
    
     state = {
          childInputVal: {}
    
     }
    

    The other option is to make this component itself a stateful component

    class Inventory extends React.Component {
        state= {
            inputValues: {}  
         }
       handleChange = (e, val) => {
            handleChange = (e, key) => {
             var childInputVal = {...this.state.inputValues}
             inputValues[key] = e.target.value
             this.setState({inputValues})
    
       }
       render() {
          let items = ['milk', 'bread', 'butter'],
          itemInput = items.map((val,index) => {
          return(
            

    {val}

    this.handleChange(e, val)}/>
    ) } return(
    {itemInput}
    ) }

提交回复
热议问题