方法一:通过event对象信息获取
import React from 'react';class Show extends React.Component {//state 相当于是Vue里面的data state = {text: "",//默认初始值 }; hanChange = ev => {//onChange 为Change事件,ev是传递的参数 console.log(ev.target.value); //1.setState不会立刻改变React组件中state的值 // 2.setState 通过触发一次组件的更新来引发重绘. // 3.多次 setState 函数调用产生的效果会合并。 this.setState({text: ev.target.value }); //点击获取文本值 console.log(this.state.text); }; render() {return (
className="App"> type="text" onChange={ev => this.hanChange(ev)} /> className='red-btn' onClick={this.handleBtnClick}>add
); }
}//导出当前模块export default Show;
方法二:使用ref,通过ref自定义一个属性名称,通过this.refs.属性名.value获取到文本的内容
import React,{Component} from 'react'export default class Show extends Component{constructor(props){super(props)this.state = {acc:'' }
}render(){return (
ref="ss"> onClick={this.aaaa.bind(this)}>提交
)
}aaaa(){console.log(this.refs.ss.value)
}
}
index.js内容如下:
import React from 'react';import ReactDOM from 'react-dom';import Show from './Show'import './style.css';ReactDOM.render( , document.getElementById('root')
);// If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: https://bit.ly/CRA-PWA
下一章: 使用react编写用户登录框
长按识别二维码,让我们一起成长吧