react组件间传值实例
时间: 2023-07-12 16:50:43 浏览: 197
好的,下面我举一个简单的例子来说明 React 组件间传值的实现。
假设我们有两个组件:`Parent` 和 `Child`,`Parent` 组件中有一个状态 `count`,`Child` 组件需要获取这个状态并显示在页面上。
1. 通过 props 传值:
```jsx
// Parent.jsx
import React, { useState } from 'react';
import Child from './Child';
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Parent Component</h1>
<p>Count: {count}</p>
<Child count={count} />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Parent;
// Child.jsx
import React from 'react';
function Child(props) {
return (
<div>
<h2>Child Component</h2>
<p>Count: {props.count}</p>
</div>
);
}
export default Child;
```
2. 通过 context 传值:
```jsx
// Parent.jsx
import React, { useState, createContext } from 'react';
import Child from './Child';
export const CountContext = createContext();
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Parent Component</h1>
<p>Count: {count}</p>
<CountContext.Provider value={count}>
<Child />
</CountContext.Provider>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Parent;
// Child.jsx
import React, { useContext } from 'react';
import { CountContext } from './Parent';
function Child() {
const count = useContext(CountContext);
return (
<div>
<h2>Child Component</h2>
<p>Count: {count}</p>
</div>
);
}
export default Child;
```
3. 通过 Redux 传值:
```jsx
// store.js
import { createStore } from 'redux';
const initialState = {
count: 0,
};
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
export default store;
// Parent.jsx
import React from 'react';
import { connect } from 'react-redux';
function Parent(props) {
const { count, dispatch } = props;
return (
<div>
<h1>Parent Component</h1>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
</div>
);
}
function mapStateToProps(state) {
return {
count: state.count,
};
}
export default connect(mapStateToProps)(Parent);
// Child.jsx
import React from 'react';
import { connect } from 'react-redux';
function Child(props) {
const { count } = props;
return (
<div>
<h2>Child Component</h2>
<p>Count: {count}</p>
</div>
);
}
function mapStateToProps(state) {
return {
count: state.count,
};
}
export default connect(mapStateToProps)(Child);
```
以上三种方式都可以实现组件间传值,具体使用哪种方式取决于应用的需求和复杂度。
阅读全文