在React中传递状态有多种方式,以下是其中几种常见的方法:
// 父组件
import React from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
status: 'active'
};
}
render() {
return (
<div>
<ChildComponent status={this.state.status} />
</div>
);
}
}
// 子组件
import React from 'react';
class ChildComponent extends React.Component {
render() {
return (
<div>
<p>Status: {this.props.status}</p>
</div>
);
}
}
// 创建Context对象
const MyContext = React.createContext();
// 父组件
import React from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
status: 'active'
};
}
render() {
return (
<MyContext.Provider value={this.state.status}>
<ChildComponent />
</MyContext.Provider>
);
}
}
// 子组件
import React from 'react';
import MyContext from './MyContext';
class ChildComponent extends React.Component {
render() {
return (
<div>
<MyContext.Consumer>
{status => <p>Status: {status}</p>}
</MyContext.Consumer>
</div>
);
}
}
// 安装Redux:npm install redux react-redux
// 创建Redux store
import { createStore } from 'redux';
const initialState = {
status: 'active'
};
function reducer(state = initialState, action) {
switch (action.type) {
case 'UPDATE_STATUS':
return { ...state, status: action.payload };
default:
return state;
}
}
const store = createStore(reducer);
// 父组件
import React from 'react';
import { connect } from 'react-redux';
class ParentComponent extends React.Component {
updateStatus = () => {
this.props.dispatch({ type: 'UPDATE_STATUS', payload: 'inactive' });
};
render() {
return (
<div>
<p>Status: {this.props.status}</p>
<button onClick={this.updateStatus}>Update Status</button>
</div>
);
}
}
const mapStateToProps = state => ({
status: state.status
});
export default connect(mapStateToProps)(ParentComponent);
// 子组件
import React from 'react';
import { connect } from 'react-redux';
class ChildComponent extends React.Component {
render() {
return (
<div>
<p>Status: {this.props.status}</p>
</div>
);
}
}
const mapStateToProps = state => ({
status: state.status
});
export default connect(mapStateToProps)(ChildComponent);
这些方法都可以在React中传递状态,具体使用哪种方法取决于你的应用场景和需求。
领取专属 10元无门槛券
手把手带您无忧上云