我有这段代码,我打印一个嵌套列表的元素。每个列表元素都有名为id
,name
和ancestors
的子节点,其中ancestors
包含其父节点,祖父节点等的名称和ID,其中以阵列形式存在的祖先。例如:
{
"name": "Child",
"id": "3",
"ancestors": [{
"name": "Father",
"id": "2"
}, {
"name": "Grandfather",
"id": "1"
}]
}
以下是代码:
export default class Child extends Component {
handleChange = (e) => {
console.log(e.target);
}
render() {
return (
<li>
<input
type="checkbox"
value={this.props.name}
id={this.props.id}
ancestors={this.props.ancestors}
onChange={(e) => this.handleChange(e)}
/>
{this.props.name}
</li>
);
}
}
我正在尝试打印此列表,每次单击一个元素时,我都需要将所单击元素的ancestor id's
作为数组发送回Parent
组件(调用方)。我可以将id
列表元素发送回Parent
组件,但我不知道如何访问id's
ancestors
节点并返回作为一个数组,因为ancestors
本身就是一个对象。
答案 0 :(得分:0)
您可以在map()
属性上使用ancestors
方法并返回ID数组。
var props = {
"name": "Child",
"id": "3",
"ancestors": [{
"name": "Father",
"id": "2"
}, {
"name": "Grandfather",
"id": "1"
}]
}
var ancestors = props.ancestors.map(({id}) => id);
console.log(ancestors)
所以你的反应代码看起来像这样。
let {Component} = React;
var data = {"name":"Child","id":"3","ancestors":[{"name":"Father","id":"2"},{"name":"Grandfather","id":"1"}]}
class Parent extends Component {
handleInputChange(ancestors) {
console.log('From parent component:', ancestors)
}
render() {
return (
<ul><Child onInputChange={this.handleInputChange} {...data} /></ul>
)
}
}
class Child extends Component {
handleChange = (e, a) => {
this.props.onInputChange(a.map(({id}) => id))
}
render() {
let {name, id, ancestors} = this.props;
return (
<li>
<input
type="checkbox"
value={name}
id={id}
ancestors={ancestors}
onChange={(e) => this.handleChange(e, ancestors)}
/>
{name}
</li>
);
}
}
ReactDOM.render(
<Parent />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>