function component中的ref屬性改寫.
這天把class component中有input ref的範例改成function component
出現錯誤Error: Function components cannot have string refs. We recommend using useRef() instead.
#### class component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import React from 'react';
class Suggest extends React.Component{ getValue(){ return this.refs.lowlevelinput.valaue; } render(){ const randomid=Math.random().toString(16).substring(2); return ( <div> <input list={randomid} defaultValue={this.props.defaultValue} ref='lowlevelinput' id={this.props.id} /> <datalist id={randomid} > {this.props.options.map((item,idx)=> <option value={item} key={idx}/> )}</datalist> </div> ); } } export default Suggest;
|
|
#### function component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import React , { useRef }from 'react';
const SuggestOpt=(props)=>{ const handleChangeValue = (event) => { console.log(inputRef.current.value); }; const handleClick = () => { inputRef.current.focus(); } const inputRef = useRef(null); const randomid=Math.random().toString(16).substring(2); return ( <div> <input list={randomid} defaultValue={props.defaultValue} ref={inputRef} id={props.id} onChange={handleChangeValue} /> <datalist id={randomid} > {props.options.map((item,idx)=> <option value={item} key={idx}/> )}</datalist> <button onClick={handleClick}>click me</button> </div> ); } export default SuggestOpt;
|
|