React 易错点

1. css的模块化

    // 作用: 避免css的污染, 只作用于当前文件
    
    .box {width: 10}
    .box2: {composes: box; height: 30}
    
    // 引入的css文件, 必须xxx.module.css
    import style from './index.module.css'
    
    // 使用box2, 达到复合多类名
    <div style={style.box2}> </div>

2. setState合并

    componentDidMount() {
        // 会合并成一次
        this.setState({counter: this.state.counter + 1});
        this.setState({counter: this.state.counter + 1});
        this.setState({counter: this.state.counter + 1});
    }

3. 新的生命周期函数(16.3)

参考: https://juejin.im/post/5aca20c96fb9a028d700e1ce

  1. getDerivedStateFromProps

  2. getSnapshotBeforeUpdate

4. ref

    // 1. 回调的ref
    
    <div ref={ div => this.divRef = div }> text </div>
    
    this.divRef
    
    // 2. 新ref
    this.inputRef = React.createRef();
    
    <div ref={this.inputRef}> text </div>
    
    this.divRef.current
    
    // 3. hook的ref, 不单单存储dom
    
    const inputEl = useRef(null);
    
    <input ref={inputEl} type="text" />
    
    inputEl.current

5. ref的转发

  1. forwardRef: 给父组件暴露具体dom
  2. useImperativeHandle: 只暴露具体dom的具体属性
  3. 参考: https://juejin.im/post/5d8f478751882509563a03b3
// 只给父组件暴露具体dom的部分属性
function FancyInput(props, ref) {
  const inputRef = useRef()
  const [text, setText] = useState('')
  
  useImperativeHandle(ref, () => ({ //第一个参数:暴露哪个ref;第二个参数:暴露什么
    focus: () => {
      inputRef.current.focus()
    },
    value: text
  }))

  const handleChange= (e) => {
    setText(e.target.value);
  }
  return <input ref={inputRef} onChange={handleChange} value={text}/>
}
FancyInput = forwardRef(FancyInput)

// 给父组件暴露具体dom
const FancyInputFn = forwardRef((props, ref) => {
  return (
    <div>
        <div ref={ref}>tes</div>
    </div>
  )
})

// 父组件获取子组件的ref
export default function App() {
  const inputRef = useRef(null)
  const inputRef2 = useRef(null)
  const handleClick = () => {
    console.log(inputRef.current, inputRef2.current);
  }
  return (
    <div>
      <FancyInput ref={inputRef}></FancyInput>
      <FancyInputFn ref={inputRef2}></FancyInputFn>
      <button onClick={handleClick}>点击</button>
    </div>
  )
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容