【发布时间】:2020-07-12 16:16:48
【问题描述】:
我主要了解发生了什么,但我不清楚 MouseTracker 组件中的渲染道具到底发生了什么。这就是我认为正在发生的事情;如果我错了,请纠正我:
MouseTracker 正在使用称为鼠标的渲染道具(状态)渲染鼠标组件。鼠标渲染道具返回 Cat 组件(传递给鼠标道具等于鼠标(状态))。
https://reactjs.org/docs/render-props.html
class Cat extends React.Component {
render() {
const mouse = this.props.mouse;
return (
<img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
);
}
}
class Mouse extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
}
handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
}
render() {
return (
<div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
{/*
Instead of providing a static representation of what <Mouse> renders,
use the `render` prop to dynamically determine what to render.
*/}
{this.props.render(this.state)}
</div>
);
}
}
class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse render={mouse => (
<Cat mouse={mouse} />
)}/>
</div>
);
}
}
【问题讨论】:
标签: reactjs jsx react-props