简体   繁体   中英

How to export React component with props?

I'm studying React.js now could you help me please how can I export React component with props? Something like this:

class Group extends React.Component {
  static propTypes = {
    children: React.PropTypes.array.isRequired
  };  
  render () {
    return <div>
        <div className='group'>
          <h2>Boys:</h2>
          <GroupList children={
              this.props.children.filter(x => x.sex === 'male')
            } />
        </div>
        <div className='group'>
          <h2>Girls:</h2>
           <GroupList children={
              this.props.children.filter(x => x.sex === 'female')
            } />
        </div>
      </div>
  }
}

React.render(<Group children={children} />, document.body)

It should be simple like "export default Group"

First thing, never render components in document.body

Second, instead of

React.render(<Group children={children} />, document.body)

Write,

export default Group

You will want to create an html element ex : ` and in your React.render should look like :

React.render(<Group />, document.getElementById("app"));

You shouldn't need to pass any props into your main component.

To export a component there are 2 ways to do so. You can either do

export default class Group extends React.Component {}

or

class Group extends React.Component { 
  ...
}
export default Group;

And then you will want to import the other components into the component you are wanting to add them in to.

Example :

import Child from './Child.jsx'
class Group extends React.Component { 
   ...
   render() {
     return (
       <Child />
     )
   }
}
export default Group;

And child would look like :

class Child extends React.Component { 
      ...
}
export default Child;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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