【React】ts react 无法使用 ref 获取input的value
使用ts 加 react 无法用ref 获取input的value值
import React, {Component} from "react"export default class Leon extends Component {
name: string;
log \= () => {
console.log("this.name:"+this.name)
}
render(): React.ReactElement<any, string | React.JSXElementConstructor<any>> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
return (
<div\>
<input ref={(input: HTMLInputElement) => this.name = input.value} type="text"/>
<button onClick={this.log}\>cccc</button>
</div>
)
}
}
获取的input.value 值为 null
回答
你需要先初始化一个 ref
, 而不是直接赋值
class Leon extends React.Component {
+ name!: string;
+ refs: any = React.createRef()
log = () => {
+ this.name = this.refs.value
console.log("this.name:" + this.name)
}
render(): React.ReactElement<any, string | React.JSXElementConstructor<any>> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
return (
<div>
+ <input ref={(input: HTMLInputElement) => this.refs = input} type="text" />
<button onClick={this.log}>cccc</button>
</div>
)
}
}
以上是 【React】ts react 无法使用 ref 获取input的value 的全部内容, 来源链接: utcz.com/a/74441.html