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. 新的生命周期函數(shù)(16.3)
參考: https://juejin.im/post/5aca20c96fb9a028d700e1ce
getDerivedStateFromProps
getSnapshotBeforeUpdate
4. ref
// 1. 回調(diào)的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的轉(zhuǎn)發(fā)
- forwardRef: 給父組件暴露具體dom
- useImperativeHandle: 只暴露具體dom的具體屬性
- 參考: https://juejin.im/post/5d8f478751882509563a03b3
// 只給父組件暴露具體dom的部分屬性
function FancyInput(props, ref) {
const inputRef = useRef()
const [text, setText] = useState('')
useImperativeHandle(ref, () => ({ //第一個參數(shù):暴露哪個ref;第二個參數(shù):暴露什么
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>
)
}