其实在react的组件中获取dom节点可以使用原生的方法,同样的react也为我们提供了获取方法
我们创建通过create-react-app一个新项目
index.html
<!doctype html> <html lang="en"> <head> <Meta charset="utf-8"> <Meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"> <Meta name="theme-color" content="#000000"> <title>React App</title> </head> <body> <div id="root"></div> </body> </html>
index.js
import React,{ Component } from 'react'; import ReactDOM from 'react-dom'; import registerServiceWorker from './registerServiceWorker'; class App extends Component { render() { return ( <div className="App"> demo <input type="text" id="input" /> </div> ); } } ReactDOM.render(<App />,document.getElementById('root')); registerServiceWorker();
切换到项目执行:
npm start
1.原生方法
这个就非常简单了,我们在结构中添加了input,给input设置一个value,然后在生命周期函数中打印出来即可,利用
import React,{ Component } from 'react'; import ReactDOM from 'react-dom'; import registerServiceWorker from './registerServiceWorker'; class App extends Component { constructor(props) { super(props); // 设置 initial state this.state = { val:"我是小a" }; } render() { return ( <div className="App"> demo <input type="text" id="input" defaultValue={this.state.val} /> </div> ); } componentDidMount () { //组件渲染完毕 console.log(document.getElementById("input").value) } } ReactDOM.render(<App />,document.getElementById('root')); registerServiceWorker();
我们可以看到结果:
3.Refs
这是react为我们提供的一个节点查找工具,我们可以给标签设置一个 ref 属性,然后在其他位置通过
this. refs.xx获取
import React,{ Component } from 'react'; import ReactDOM from 'react-dom'; import registerServiceWorker from './registerServiceWorker'; class App extends Component { constructor(props) { super(props); // 设置 initial state this.state = { val:"我是小a" }; } render() { return ( <div className="App"> demo <input type="text" defaultValue={this.state.val} ref="input" /> </div> ); } componentDidMount () { //组件渲染完毕 console.log(this.refs.input.value) } } ReactDOM.render(<App />,document.getElementById('root')); registerServiceWorker();
2.findDOMNode
这个方法我们也是返回dom节点,是通过
ReactDOM.findDOMNode()
import React,{ Component } from 'react'; import ReactDOM from 'react-dom'; import registerServiceWorker from './registerServiceWorker'; class App extends Component { constructor(props) { super(props); // 设置 initial state this.state = { val:"我是小a" }; } render() { return ( <div className="App"> demo <input type="text" id="input2" defaultValue={this.state.val} ref="input" /> </div> ); } componentDidMount () { //组件渲染完毕 console.log(ReactDOM.findDOMNode(this.refs.input)) } } ReactDOM.render(<App />,document.getElementById('root')); registerServiceWorker();