react兄弟组件调用方法
时间: 2023-11-08 11:03:33 浏览: 49
在 React 中,兄弟组件之间的通信需要通过共同的父组件来实现。兄弟组件可以通过父组件来共享方法,然后通过 props 将方法传递给需要调用的组件。
以下是一个示例,演示了如何在兄弟组件之间调用方法:
```jsx
// 父组件
import React, { useState } from 'react';
import BrotherA from './BrotherA';
import BrotherB from './BrotherB';
function Parent() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<div>
<BrotherA incrementCount={incrementCount} />
<BrotherB count={count} />
</div>
);
}
// BrotherA 组件
import React from 'react';
function BrotherA({ incrementCount }) {
return (
<div>
<button onClick={incrementCount}>增加计数</button>
</div>
);
}
// BrotherB 组件
import React from 'react';
function BrotherB({ count }) {
return (
<div>
<p>计数: {count}</p>
</div>
);
}
```
在上面的示例中,Parent 组件维护了一个 count 状态,并通过 incrementCount 方法来增加计数。BrotherA 组件中的按钮绑定了 incrementCount 方法,当按钮被点击时,会调用该方法来增加计数。然后,Parent 组件将 count 通过 props 传递给 BrotherB 组件,用于展示当前的计数。