嗨,我有这个代码与对象:
const data = [{
item1: {
ans1: "Ich",
ans2: "Du",
ans3: "Jemand",
ans4: "Egal",
correct: 3,
quest: "Wer hat die Kokosnuss geklaut?"
}];
和此:
render() {
const hereGoesMyLevelNum = this.state.level;
const answers = data.map((answer) => {
return (
<ul>
<li>{answer.item1.ans1}</li>
<li>{answer.item1.ans2}</li>
<li>{answer.item1.ans3}</li>
<li>{answer.item1.ans4}</li>
</ul>
)
});
return (
<div className="App">
<ul>{answers}</ul>
</div>
);}} export default App;
我想得到&#34; answers.items&#34;通过将级别编号从状态传递给它来动态生成。 类似的东西:
{answer.item{hereGoesMyLevelNum}.ans1}
你能帮帮我吗? :)
答案 0 :(得分:2)
使用这样的方括号
{answer["item"+hereGoesMyLevelNum].ans1}
答案 1 :(得分:0)
您可以使用Es6 Computed property keys语法(结合ES6 Template literals)。
计算属性键
const id = 1;
const myKeyName = 'key' + id;
myObject[myKeyName]
与模板文字相结合
const id = 1;
const myKeyName = `key${id}`;
myObject[myKeyName]
运行示例:
const data = [
{
item1: {
ans1: "Ich",
ans2: "Du",
ans3: "Jemand",
ans4: "Egal",
correct: 3,
quest: "Wer hat die Kokosnuss geklaut?"
}
}
];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
level: 1
};
}
render() {
const hereGoesMyLevelNum = this.state.level;
return (
<div>
{
data.map((answer) => {
const lvlAnswer = `item${hereGoesMyLevelNum}`;
return (
<ul>
<li>{answer[lvlAnswer].ans1}</li>
<li>{answer[lvlAnswer].ans2}</li>
<li>{answer[lvlAnswer].ans3}</li>
<li>{answer[lvlAnswer].ans4}</li>
</ul>
)
})
}
</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>
答案 2 :(得分:0)
您可以使用Object.keys()
从对象中动态获取属性名称。
示例强>
rating high low medium
1 158 1 36
2 77 2 25
3 106 10 36
4 82 56 71
5 60 97 62
如果您的对象中只有一个属性,则可以执行以下操作。
Dim myProcesses() As Process Dim myProcess As Process
' How to retrieve the program associat with pdf, when i only know the file extension ?
myProcesses = Process.GetProcessesByName("AcroRd32") For Each myProcess In myProcesses
If Date.Now.Ticks - myProcess.StartTime.Ticks > TimeSpan.FromSeconds(30).Ticks Then
myProcess.Kill()
End If
Next