繁体   English   中英

ReactJS:从父组件道具传递要映射的道具是未定义的

[英]ReactJS: Passing props to map from parent component props are undefined

我在map()函数中创建了<textarea>元素,并且在渲染组件时试图在每个元素中获取不同的值。

// Inside render method of ComponentA

fruits.map((fruit) => {
  return <textarea name={fruit.title} value={this.props.fruit.title} onChange={this.props.handleChange}
})

这样可以正确设置name={fruit.title} ,但是对于prop name={fruit.title} value ,它给我一个错误,是title undefined

从字面上看,它似乎是this.props.fruit东西,而不是fruit.title的值。

我想传递不同的价值支持,以便可以从父组件中以以下方式使用它:

// State and rendered components inside ComponentB

state = {
  apple: '',
  orange: ''
}

handleChange = (e) => {
  const name = e.target.name;
  const value = e.target.value;
  this.setState(
     { [name]: value }
  );
}

<componentA
  handleChange={this.handleChange}
  apple={this.state.apple}
  orange={this.state.orange}
/>

这看起来像是映射函数中有小错误的情况。 尝试更换:

value={this.props.fruit.title}

附:

value={fruit.title}

map()回调返回的<textarea>元素上。

另外,由于要在循环中渲染文本区域,因此请确保通过替换以下内容正确调用onChange

onChange={this.props.handleChange}

附:

onChange={e => this.props.handleChange(e)}

另外,请考虑向<textarea/>添加唯一的key道具,以确保map()函数中元素列表的正确呈现,如下所示:

fruits.map((fruit, index) => {
  return <textarea name={fruit.title} value={fruit.title} key={index} onChange={e => this.props.handleChange(e)}></textarea>
})

尝试这个:

state = {
  fruits:[{title:'apple'},{title:'orange'}]
};

<SubmitForm
 handleChange={this.handleChange}
 fruits={[this.state.fruits]}
/>

为了实现您的要求,请考虑以下ComponentA实现:

class ComponentA extends React.Component {

    render() {

        // Create a local array from apply and orange props
        const fruits = [ this.props.apple, this.props.orange ];

        // Map over the fruits and render each textarea as required
        return (<div>{ 
            fruits.map((fruit, index) => {
                return <textarea key={index}
                                 name={fruit} 
                                 value={fruit} 
                                 onChange={this.props.handleChange}></textarea>
            })</div>)    
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM