资讯专栏INFORMATION COLUMN

React 表单元素

894974231 / 3304人阅读

摘要:今天来讲讲的表单元素。在中,并不使用之前的属性,而在根标签上用属性来表示选中项。多个输入的解决方法当你有处理多个受控的元素时,你可以通过给每个元素添加一个属性,来让处理函数根据的值来选择做什么。

今天来讲讲react的表单元素。
受控元素
下面来看一下如何获取输入框的值

import React, { Component } from "react";

class Trem extends React.Component {
    constructor(props){
        super(props);
        this.inp = this.inp.bind(this);
        this.sub = this.sub.bind(this);
        this.state = {
            place:"请输入...",
            inputV:""
        }
    };
    inp(e){
        this.setState({
            inputV:e.target.value     {/* 通过事件细节改变inputV的值*/}
        });
        console.log(e.target.value)
    };    
    sub(){
      console.log(this.state.inputV)
    };    
    render(){
        return (
            

{/*此处的main是来自父组件的传值*/}
) } } export default Trem;

代码解读:
this.inp = this.inp.bind(this); 绑定inp函数this指向
this.state 初始化变量
inp() 监听input的输入值
this.state.inputV 通过赋值获取input的value

textarea 标签

import React, { Component } from "react";

class Trem extends React.Component {
    constructor(props){
        super(props);
        this.inp = this.inp.bind(this);
        this.sub = this.sub.bind(this);
        this.state = {
            place:"请输入...",
            inputV:""
        }
    };
    inp(e){
        this.setState({
            inputV:e.target.value    
        });
        console.log(e.target.value)
    };    
    sub(){
      console.log(this.state.inputV)
    };    
    render(){
        return (