使用React

时间:2017-11-22 16:34:17

标签: javascript reactjs

我有这段代码,我打印一个嵌套列表的元素。每个列表元素都有名为idnameancestors的子节点,其中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本身就是一个对象。

1 个答案:

答案 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>