如何输出我的州的关键和价值?

问题描述 投票:0回答:1

我希望能够输出状态中项目键的键和值。我尝试使用{[this.state[field]]},但这也不起作用。

示例:https://jsfiddle.net/n5u2wwjg/164470/

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        type: 'valueOfType',
        subType: 'valueOfSubType',
        anotherThing: 'valueOfOther'
    }
  }

  renderItem = (field) => {
     return <div>{['nameOfKey']}: {field}</div>
  }

  render() {
    const { type, subType, anotherThing } = this.state;
    return (
      <div>
        <p><strong>Actual output:</strong></p>
        {this.renderItem(type)}
        {this.renderItem(subType)}
        {this.renderItem(anotherThing)}

        <hr/>
        <p><strong>Desired output:</strong></p>
        <div>type: valueOfType</div>
        <div>subType: valueOfSubType</div>
        <div>anotherThing: valueOfOther</div>
     </div>
    )
  }
}
javascript reactjs object
1个回答
0
投票

正如@ Li357建议您可以将密钥作为字符串传递,并在方法中像this.state[field]一样使用它。或者,您可以使用Object.entriesmap渲染所有字段。

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      type: 'valueOfType',
      subType: 'valueOfSubType',
      anotherThing: 'valueOfOther'
    }
  }

  renderItem = (field) => {
    return <div>{field}: {this.state[field]}</div>
  }

  renderAll = () => Object.entries( this.state ).map( ([key,value]) =>
    <p>{key}:{value}</p>
  );

  render() {
    return (
      <div>
        <p><strong>Actual output:</strong></p>
        {this.renderItem("type")}
        {this.renderItem("subType")}
        {this.renderItem("anotherThing")}

        <hr />
        {this.renderAll()}

        <hr />
        <p><strong>Desired output:</strong></p>
        <div>type: valueOfType</div>
        <div>subType: valueOfSubType</div>
        <div>anotherThing: valueOfOther</div>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>
© www.soinside.com 2019 - 2024. All rights reserved.