Appearance
父组件调用子组件方法
render props
json
class Wrapper extends React.Component {
state = {
count: 0
};
confirm = () => {
window.alert(1)
}
// Increase count
increment = () => {
const { count } = this.state;
return this.setState({ count: count + 2 });
};
// Decrease count
decrement = () => {
const { count } = this.state;
return this.setState({ count: count - 1 });
};
render() {
const { count } = this.state;
return (
<div>
{this.props.render({
increment: this.increment,
decrement: this.decrement,
confirm: this.confirm,
count: count
})}
</div>
);
}
}
class App extends React.Component {
render() {
return (
<Wrapper
render={({ increment, decrement, confirm, count }) => (
<div>
<div>
<h3>Render Props Counter</h3>
</div>
<div>
<p>{count}</p>
<button onClick={() => increment()}>Increment</button>
<button onClick={() => decrement()}>Decrement</button>
<button onClick={confirm}>confirm</button>
</div>
</div>
)}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));useImperativeHandle + forwardRef
更新: 2023-07-27 14:42:43
原文: https://www.yuque.com/u3641/dxlfpu/pnt65e