【问题标题】:Passing a variable from Child component to Parent component将变量从子组件传递到父组件
【发布时间】:2020-10-17 14:04:42
【问题描述】:

我没有从子组件的event => { this.handleChange(event, index) } 中获得index,我怀疑event 也没有到达。我不知道如何将其传递给父母。我曾尝试将其添加到孩子的props.onChange(event, index) 中,但没有奏效。我已经尽可能多地摆弄,但被卡住了。任何帮助将不胜感激!

家长:

 <Inputs hasInputs={hasInputs} onSubmit={this.handleSubmit} thoughtProp={this.state.thought} onChange={event => { this.handleChange(event, index) }} />

孩子:


export const Inputs = (props) => {
    return (
        <form className="flex-item-main form" onSubmit={props.onSubmit}>
        <div>
                    <h4>
                      <p className='inputsHeader'>Thoughts:</p>  
                    </h4>
                </div>
            <ol>
              {props.thoughtProp.map((input, index) => (
                <Input type='text' key={index} value={input} onChange={props.onChange} className='textInputs' />
              ))}
              { props.hasInputs ? (
                <input className='submitThoughts' type='submit' value='Submit Thought!' />
              ) : (
                null
              )}
            </ol>
          </form>
    )
}

【问题讨论】:

    标签: javascript reactjs variables components react-props


    【解决方案1】:

    你还需要传递索引

    在父级中

    onChange={this.handleChange}
    

    在孩子身上

    onChange={(e) => props.onChange(e, index)}
    

    【讨论】:

    • 我收到错误props.onChange is not a function
    • 你的父组件是类组件,你的子组件是函数组件吗?
    • 没错,父类组件和子函数
    • 嗯,这很奇怪,我使用我在答案codesandbox.io/s/confident-dust-cxk29?file=/src/App.js 中输入的相同的工作示例创建了这个代码框
    • 你是对的,一定是别的东西。射击。唔。好的。回到绘图板。
    猜你喜欢
    • 2019-02-24
    • 2020-07-23
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2019-01-04
    • 2019-01-21
    • 2019-02-27
    • 2017-04-20
    相关资源
    最近更新 更多