Where is Children from mapStateToProps in redux of

2019-07-22 05:09发布

问题:

in https://redux.js.org/basics/exampletodolist#containers-filterlink-js, the code of FilterLink.js is

import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'
​
const mapStateToProps = (state, ownProps) => ({
  active: ownProps.filter === state.visibilityFilter
})
​
const mapDispatchToProps = (dispatch, ownProps) => ({
  onClick: () => dispatch(setVisibilityFilter(ownProps.filter))
})
​
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Link)

We can find obviously, active and onClick is passed to Link component

However, in Link component, https://redux.js.org/basics/exampletodolist#components-link-js, the code is

import React from 'react'
import PropTypes from 'prop-types'
​
const Link = ({ active, children, onClick }) => (
  <button
    onClick={onClick}
    disabled={active}
    style={{
      marginLeft: '4px'
    }}
  >
    {children}
  </button>
)
​
Link.propTypes = {
  active: PropTypes.bool.isRequired,
  children: PropTypes.node.isRequired,
  onClick: PropTypes.func.isRequired
}
​
export default Link

Where does children in Link props come from?

回答1:

Everything that resides inside the component is children:

<Link>
I am children
</Link>


props.children // I am children


<MyComponent>
  <div>
   <h1>The root div element is called children here 
     which can contain several elements and/or components.</h1>
  </div>
</MyComponent>


<MainComponent>
  <ChildComponent /> {/* children to MainComponent */}
</MainComponent>

It's just how react props is passed.



标签: reactjs redux