Voi*_*Mập 6 javascript reactjs
我试过2小时来渲染1个对象.
我的对象是:
const ObjectTest = {
1: {
id : 1,
name:'ABC'
},
3: {
id: 3,
name:'DEF'
}
}
Run Code Online (Sandbox Code Playgroud)
我想渲染:
id is 1 ; name is ABC
id is 3 ; name is DEF
Run Code Online (Sandbox Code Playgroud)
我想在一个函数中创建这个对象,并在render函数中调用.
谁能帮我?感谢所有提前:)
May*_*kla 15
数据是一个对象所以直接我们不能使用map,所以使用Object.keys或Object.entries首先获取数组,然后使用map它来创建ui项.
使用Object.keys:
_renderObject(){
return Object.keys(ObjectTest).map(obj, i) => {
return (
<div>
id is: {ObjectTest[obj].id} ;
name is: {ObjectTest[obj].name}
</div>
)
})
}
Run Code Online (Sandbox Code Playgroud)
const ObjectTest = {
1: {
id : 1,
name:'ABC'
},
3: {
id: 3,
name:'DEF'
}
}
class App extends React.Component{
_renderObject(){
return Object.entries(ObjectTest).map(([key, value], i) => {
return (
<div key={key}>
id is: {value.id} ;
name is: {value.name}
</div>
)
})
}
render(){
return(
<div>
{this._renderObject()}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))Run Code Online (Sandbox Code Playgroud)
<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='app'/>Run Code Online (Sandbox Code Playgroud)
还检查这个答案:如何在ReactJS中循环一个对象?
小智 13
all these mappings... Bruh. Use "pre" tag with JSON.stringify
<pre>
{JSON.stringify(yourdataobject, null, 2)}
</pre>
Run Code Online (Sandbox Code Playgroud)
The pre tag stands for preformatted text. It just means that whatever is inside is displayed as fixed width and preserves line breaks and whitespace (as written in the HTML code).
JSON.stringify does exactly what it sounds like - turns the object passed in the first argument into a JSON string. The 2nd argument is a replacer function that's not relevant here. The 3rd argument is how much indentation to use - in this case, 2 spaces (which will be be preserved due to the pre tag).
| 归档时间: |
|
| 查看次数: |
20827 次 |
| 最近记录: |