title | date | tags | categories | ||
---|---|---|---|---|---|
HOC的学习 |
2019-10-31 |
|
|
-
操纵 props 需求 1: 我想给每一个组件添加一个 props。
import React from 'react'; import A from './A'; import B from './B'; function App() { return ( <div className="App"> <A name="andy" age={22} /> <B name="rabbit" age={21} /> </div> ); } export default App;
import React from 'react'; import HOComponent from './HOC/HOComponent'; const A = ({ name, age, sex }) => { return ( <div> 我是组件A: <p>我的英文名是: {name}</p> <p>我的年龄是: {age}</p> <p>我的性别是: {sex}</p> </div> ); }; export default HOComponent()(A);
import React, { Component } from 'react'; const HOComponent = () => WrapComponent => class HOC extends Component { render() { return <WrapComponent sex="男" {...this.props}></WrapComponent>; } }; export default HOComponent;
需求2: 删除指定一个props。比如name
import React, { Component } from 'react'; const HOComponent = () => WrapComponent => class HOC extends Component { render() { const { name, ...otherProps } = this.props; return <WrapComponent sex="男" {...otherProps}></WrapComponent>; } }; export default HOComponent;
-
抽取状态 需求1: A跟B需要一个Input组件(受控),用尽可能少的代码完成。
import React from 'react'; import HOComponent from './HOC/HOComponent'; const A = (props) => { const { name, age, sex, ...otherProps } = props; return ( <div> 我是组件A: <p>我的英文名是: {name}</p> <p>我的年龄是: {age}</p> <p>我的性别是: {sex}</p> <input {...otherProps} /> </div> ); }; export default HOComponent()(A);
import React, { Component } from 'react'; const HOComponent = () => WrapComponent => class HOC extends Component { state = { value: '' } handleInputChange = e => { this.setState({ value: e.target.value }); } render() { const { name, ...otherProps } = this.props; const { value } = this.state; const InputProps = { value, onChange: this.handleInputChange } return <WrapComponent sex="男" {...InputProps} {...otherProps}></WrapComponent>; } }; export default HOComponent;
-
访问 ref
-
包装组件