如何通过React为div设置动态数据?

时间:2019-02-24 12:24:57

标签: reactjs

我点击了onClick={e => this.handelrule(e, element.families[j], index)}<span class="text" key={index}>{this.state.text[index]}</span>的文本应为test,并且测试将是动态的。我把test当作测试,但没有设置。

我必须在renderDetail中调用DetailsInfo函数,而不是在渲染时间上进行设置。我无法在渲染时将其称为renderDetail函数。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      DetailsInfo: {},
      text: {}
    };
  }

  render() {
    const { data } = this.state;
    const renderInfo = data.map((item, i) => {
      return (
        <div class="item">
          <div class="moreInfo" onClick={e => this.showDiv(e, item, i)}>
            <span>show more data</span>
          </div>
          <div class="table">{this.state.DetailsInfo[i]}</div>
        </div>
      );
    });
    return <div>{renderInfo}</div>;
  }

  showDiv = (e, element, i) => {
    this.setState(prevState => ({
      DetailsInfo: {
        ...prevState.DetailsInfo,
        [i]: this.renderDetails(element, i)
      }
    }));
  };

  renderDetails(element, i) {
    let lenfamilies = element.families.length;
    var indents = [];
    var index = 0;
    for (var j = 0; j < lenfamilies; j++) {
      var numF = i;
      var numS = j;
      var stingF = numF.toString();
      var stingS = numS.toString();
      index = stingF + stingS;
      indents.push(
        <div>
          <span
            key={index}
            onClick={e => this.handelrule(e, element.families[j], index)}
          >
            Click
          </span>
          <span class="text" key={index}>
            {this.state.text[index]}
          </span>
        </div>
      );
    }
    return indents;
  }

  handelrule = (e, element, index) => {
    console.log(index);
    this.setState(prevState => ({
      text: { ...prevState.text, [index]: "test" }
    })); ////In this part 'test' should be set in  div by class="text"
  };
}

ReactDOM.render(<App />, document.getElementById("Result"));

0 个答案:

没有答案