我希望能够输出状态下的项的键和键的值。我尝试使用{[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>
)
}
}
答案 0 :(得分:0)
如@ Li357所建议的那样,您可以将密钥作为字符串传递,并在方法中像this.state[field]
一样使用它。另外,您可以使用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>