1. 程式人生 > 其它 >react之ref屬性和事件處理屬性

react之ref屬性和事件處理屬性

技術標籤:需理解# reacthtmlreactjavascriptjs

程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>06_component_refs_event</title>
    <script src="../js/react.development.js"></script>
    <script src
="../js/react-dom.development.js">
</script> <script src="../js/prop-types.js"></script> <script src="../js/babel.min.js"></script> </head> <body> <div id="example"></div> <div id="example1">
</div> <div id="example2"></div> <script type="text/babel"> //1.定義元件 class MyComponent extends React.Component{ constructor(props) { super(props) this.showInput = this.showInput.bind(this) this.newShowInput =
this.newShowInput.bind(this) this.handleBlur = this.handleBlur.bind(this) } showInput() { const input = this.refs.content; alert(input.value) } newShowInput() { alert(this.something.value) } handleBlur(event) { alert(event.target.value) } render(){ return( <div> <input type="text" ref="content"/>&nbsp;&nbsp; <button onClick={this.showInput}>舊版本提示輸入</button>&nbsp;&nbsp; <input type="text" ref={input => this.something = input}/>&nbsp;&nbsp; <button onClick={this.newShowInput}>新版本</button>&nbsp;&nbsp; <input type="text" placeholder="失去焦點提示內容" onBlur={this.handleBlur}/> </div> ) } } //2.渲染元件標籤 ReactDOM.render(<MyComponent />,document.getElementById("example"))
</script> </body> </html>

程式碼講解

  1. this.refs.content指的是該類ref=content的元素,ref屬性是該元素的標識,相當於HTML中的id屬性。
  2. 新版本的ref屬性是這樣賦值的,其中,input指這個標籤名字(我試過將此處的input改為aaa也能夠實現功能,但是視訊說的是什麼標籤就用什麼名字,),something為自命名
<input type="text" ref={input => this.something = input}/>&nbsp;&nbsp;
  1. placeholder屬性為背景提示內容
    在這裡插入圖片描述
  2. event.target.value的值是呼叫這個方法的元素的input輸入值