简体   繁体   English

如何将状态数组转移到道具

[英]How to transfer a state array to props

So I have 2 React files, an App.js and a category.js. 所以我有2个React文件,一个App.js和一个category.js。 When I transfer my array to category.js, it shows a huge blob of text instead of splitting it into different array buttons. 当我将数组传输到category.js时,它显示了大量文本,而不是将其拆分为不同的数组按钮。 I tried searching but I don't understand how to do it. 我尝试搜索,但不知道该怎么做。 Can someone explain it? 有人可以解释吗?

here is the class App 这是班级的应用程序

class App extends React.Component {
Object.keys(data.categories).forEach((category,index) => {
    arr.push(data.categories[index].name);
})

render() {
return (
<div>
    <Categories 
      categoryName = { this.state.categoryName }
    />
</div>

and here is the categories using props 这是使用道具的类别

const Categories = props => (
<div>
    <br /> 
    { props.categoryName && <button> { props.categoryName } </button>}
</div>
);

You need to map over your categoryName array 您需要映射您的categoryName数组

const Categories = props => (
   <div>
      <br /> 
      { props.categoryName &&
        props.categoryName.map(name => <button>{name}</button>)}
   </div>
   );

Assuming your categories are an array of objects in your component state, map over the state categories and return a Category component with each iteration of the array. 假设类别是组件状态中的对象数组,请map状态类别,并在数组的每次迭代中返回Category组件。

 function Category({ categoryName }) { return (<button>{categoryName}</button>); } class App extends React.Component { constructor(props) { super(props); this.state = { categories: [ { categoryName: 'Bob', type: 'string' }, { categoryName: 'Trevor', type: 'number' }] }; } render() { return ( <div> {this.state.categories.map(category => { return <Category categoryName={category.categoryName} /> })} </div> ) } } ReactDOM.render( <App />, document.getElementById('container') ); 
 <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="container"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM