通過傳遞ref prop給 styled component 將獲得:
const Input = styled.input` padding: 0.5em; margin: 0.5em; color: palevioletred; background: papayawhip; border: none; border-radius: 3px; `; class Form extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } render() { return ( <Input ref={this.inputRef} placeholder="Hover to focus!" onMouseEnter={() => { this.inputRef.current.focus() }} /> ); } } render( <Form /> );
注意v3 或更低的版本請(qǐng)使用 innerRef prop instead.
更多建議: