单击子元素数组

时间:2018-06-02 20:18:25

标签: javascript reactjs

我试图让这些子元素单独点击。当我点击这些子元素时,我想让它读作“点击”。

供参考:state = {         清单:[{sublist:[           “约翰尼”           “卡尔”]}         ]       }

import React, { Component } from 'react';
import './App.css';
import Comp from './Comp';

class App extends Component {

  state = {
    list: [ { sublist: [
      "johnny", 
      "carl"]}
    ]
  }

  changetext = event => {
    //const { textContent } = event.target;
    const textContent = event.target.textContent;
    // Always use the callback syntax for setState when you need to refer to the previous state

    this.setState(
      {list: this.state.list[0].sublist.map(el => textContent === el ? "clicked" : el)});
  }

  render() {

    return (
      <div>
        <Comp list = {this.state.list}
        changetext = {this.changetext}/> 
      </div>
    );
  }
}

export default App;

这是我发送迭代状态并显示div列表的地方。我想让每个可点击并将文本更改为“clicked”列表的每个子元素。

当我设置state = {list:[“johny”,“carl”]}没有内部对象和对象中的另一个数组时,这很好。(另外,设置{props.list [0] .sublist [ i]}到props.list [i])。但是当我尝试相同的方法来读取子列表时,它就会崩溃,我会在底部得到错误。

import React from 'react';

const Comp = props => {

    let listarr = [];

    for(let i = 0; i < 3; i++)
    {
        listarr[i] = <div key={i} onClick={props.changetext}>{props.list[0].sublist[i]}</div>;
    }

    return(
        <div>{listarr}</div>

    );
}

export default Comp;

当我尝试单击每个元素时,我收到以下错误:

TypeError: Cannot read property '0' of undefined
Comp
C:/Users/cburzo/Desktop/reactest3/src/Comp.js:12
   9 | 
  10 |    for(let i = 0; i < 3; i++)
  11 |    {
> 12 |        listarr[i] = <div key={i} onClick={props.changetext}>{props.list[0].sublist[i]}</div>;
  13 |    }
  14 |    
  15 |    return(
View compiled
▶ 15 stack frames were collapsed

1 个答案:

答案 0 :(得分:2)

你正在设置你的状态错误,map返回一个数组并将它分配给列表,这不是你的初始状态是如何被构造的,你想要的是:

  this.setState({
      list: [
        {
          sublist: this.state.list[0].sublist.map(
            el => (textContent === el ? "clicked" : el)
          )
        }
      ]
    });