我有以下代码:
export class Highlights extends React.Component { render() { return ( <div> {JSON.stringify(this.props.highlights_data.data)} </div> ) } }
打印出以下内容:
{“ active”:{“ label”:“ Active”,“ value”:“ 12”},“ automatic”:{“ label”:“ Automatic”,“ value”:“ 8”},“ waiting”:{ “ label”:“正在等待”,“ value”:“ 1”},“ manual”:{“ label”:“ Manual”,“ value”:“ 3”}}
我怎样才能遍历highlights_data.data道具调用另一个组件传承label和value?
highlights_data.data
label
value
除了@Dan的答案,我认为其他答案对您没有帮助/有用,因为它们不会遍历您的JSON对象。
为了正确执行此操作,您需要遍历JSON对象中的每个键。您可以通过几种方法来执行此操作,其中之一是使用Object.keys()。像下面的代码片段。
Object.keys()
此解决方案遍历JSON对象中的每个键,并将其推入数组。一旦有了该数组,就可以map()像往常一样使用遍历它,并将相关的props传递给另一个子组件。
map()
class MyApp extends React.Component { render() { var json = {"active":{"label":"Active","value":"12"},"automatic":{"label":"Automatic","value":"8"},"waiting":{"label":"Waiting","value":"1"},"manual":{"label":"Manual","value":"3"}}; var arr = []; Object.keys(json).forEach(function(key) { arr.push(json[key]); }); return <ul>{arr.map(item => <MyAppChild key={item.label} label={item.label} value={item.value} />)}</ul>; } } class MyAppChild extends React.Component { render() { return <li>{this.props.label + " - " + this.props.value}</li>; } } ReactDOM.render(<MyApp />, document.getElementById('myapp')); <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="myapp"></div>