Javascript ReactJS:未定义从父组件道具向地图传递道具
我在Javascript ReactJS:未定义从父组件道具向地图传递道具,javascript,reactjs,dictionary,Javascript,Reactjs,Dictionary,我在map()函数中创建了元素,在渲染组件时,我试图在每个元素中获得不同的值 // Inside render method of ComponentA fruits.map((fruit) => { return <textarea name={fruit.title} value={this.props.fruit.title} onChange={this.props.handleChange} }) 这看起来像是映射函数中的一个小错误。尝试替换: onChange={
map()
函数中创建了
元素,在渲染组件时,我试图在每个元素中获得不同的值
// Inside render method of ComponentA
fruits.map((fruit) => {
return <textarea name={fruit.title} value={this.props.fruit.title} onChange={this.props.handleChange}
})
这看起来像是映射函数中的一个小错误。尝试替换:
onChange={this.props.handleChange}
value={this.props.fruit.title}
与:
value={fruit.title}
在从map()
回调返回的
元素上
另外,由于在循环中呈现textarea,请通过替换以下内容确保正确调用onChange
:
onChange={this.props.handleChange}
与:
也可以考虑在代码< >代码>中添加唯一的<代码>键<代码> PROP,以确保在<代码>(或)/代码>函数中的元素列表的正确呈现,如:
fruits.map((fruit, index) => {
return <textarea name={fruit.title} value={fruit.title} key={index} onChange={e => this.props.handleChange(e)}></textarea>
})
fruits.map((水果,索引)=>{
返回此.props.handleChange(e)}>
})
试试这个:
state = {
fruits:[{title:'apple'},{title:'orange'}]
};
<SubmitForm
handleChange={this.handleChange}
fruits={[this.state.fruits]}
/>
状态={
水果:[{title:'apple'},{title:'orange'}]
};
<代码> > p>为了实现您所需要的,请考虑以下代码实现:<代码>组件< /代码>:
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>)
}
}
类组件A扩展了React.Component{
render(){
//使用apply和orange道具创建本地数组
常量水果=[this.props.apple,this.props.orange];
//映射到水果上,并根据需要渲染每个文本区域
返回({
水果.map((水果,索引)=>{
回来
}))
}
}
是的,但我希望{fruit.title}
成为道具。比如,这个.props.apple
,这个.props.orange
在映射函数中,所以你想访问映射()中的状态
对象
function?是的,在组件B中例如OOPS对不起,是!!在我的示例中必须是组件A,my bad,将对其进行编辑now@DacreDenny我编辑了您的答案以突出显示两件事1.在渲染过程中限制onChange调用2.在地图内的textarea中添加唯一键。您认为如何?这不会解决OP问题。请看Dacre Denny回答你在哪里使用水果?数组中没有标题。Ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.索引作为键始终是第二个选项
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>)
}
}