This time I will show you how to share data in react components, and what are the precautions for sharing data in react components. The following is a practical case, let's take a look.
Use react-redux to realize data sharing between react component data
1. Install react-redux
$ npm i --save react-redux
2. Import from react-redux The Proper component assigns the store to the Provider's store attribute, and
wraps the root component with the Provider.
import {Provider,connect} from 'react-redux' ReactDOM.render( <Provider store={store}> <Wrap/> </Provider>,document.getElementById('example'))
In this way, all sub-components in the root component can obtain the value in the store
3.connect secondary encapsulation of the root component
export default connect(mapStateToProps,mapDispatchToProps)(Wrap)
connect receives two functions as parameters , a mapStateToProps defines which store properties will be mapped to properties on the root component (pass the store into the react component), and a mapDispatchToProps defines which actions can be used as root component properties (pass the data from the react component into the store)
3. Define these two mapping functions
function mapStateToProps(state){ return { name:state.name, pass:state.pass } } function mapDispatchToProps(dispatch){ return {actions:bindActionCreators(actions,dispatch) } }
Map the name and pass in the store to the name and pass attributes of the root component.
actions is an object that contains the action construction function. Use bindActionCreators to bind the object actions to the actions attribute of the root component.
4. Use <Show name={this.props.name} pass={this.props.pass}></Show>## where the root component refers to the sub-component. #Transfer store data into the subcomponent.
<Input actions={this.props.actions} ></Input>
//Input组件 export default class Input extends React.Component{ sure(){ this.props.actions.add({name:this.refs.name.value,pass:this.refs.pass.value}) } render(){ return ( <p> 姓名:<input ref="name" type="text"/> 密码:<input ref="pass" type="text"/> <button onClick={this.sure.bind(this)}>登录</button> </p> ) } }
Use JS to operate pictures and leave only black and white
How to use vue components in actual projects
The above is the detailed content of How to share data within react components. For more information, please follow other related articles on the PHP Chinese website!