Render Props
- 컴포넌트는 React에서 코드의 재사용성을 위해 사용하는 주요 단위입니다. 하지만 컴포넌트에서 캡슐화된 상태나 동작을 같은 상태를 가진 다른 컴포넌트와 공유하는 방법이 항상 명확하지 않다.
- 컴포넌트 안에서 사용된 행위를 다른 컴포넌트에서 재사용하려면 render propr를 사용하여 다른 컴포넌트를 동적으로 렌더링해준다.
class RenderProp extends React.Component {
constructor(props) {
super(props);
this.sayHello = this.sayHello.bind(this);
this.state = { say: 0 };
}
sayHello(e) {
this.setState({ say: ++this.state.say });
}
render() {
return (
<>
<div onClick={(e) => this.sayHello(e)}>Hello</div>
{this.props.render(this.state)}
</>
);
}
}
const Hello = ({ count }) => {
console.log(count);
const { say } = count;
return <div>{say}</div>;
};
const App = () => {
return <RenderProp render={(count) => <Hello count={count} />} />;
};
export default App;