[英]How can I output both the key and value of my state?
I want to be able to output both the key and the value of the key of items in my state. 我希望能够在我的状态下同时输出项的键和键的值。 I tried using
{[this.state[field]]}
but that didn't work either. 我尝试使用
{[this.state[field]]}
但这也不起作用。
Example: https://jsfiddle.net/n5u2wwjg/164470/ 示例: 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>
)
}
}
As @Li357 suggested you can pass the key as a string and use it like this.state[field]
in your method. 就像@ Li357所建议的那样,您可以将密钥作为字符串传递,并在方法中像
this.state[field]
一样使用它。 Alternatively, you can use Object.entries
and map
to render all the fields. 或者,您可以使用
Object.entries
和map
来呈现所有字段。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.