1.首先我们应该清楚两个东西,state和setState ,一个是状态,一个是设置状态,我们就可以在状态中添加一些默认的数据,然后用setState来改变state,此时,会触发render()从新来渲染页面,

代码如下:命名很乱,能懂意思就行,

import React, { Component } from 'react';
class App extends Component {
constructor(props){
      super(props);
      this.fn = this.fn.bind(this);
      this.wode = this.wode.bind(this);
      this.hand = this.hand.bind(this);   
      this.tade = this.tade.bind(this);
      this.nide = this.nide.bind(this);    
      //设置初始值  
      this.state={
          a:'',
          b:'',
          c:'',
          d:''
      }
     
 };
 //获取input中的值,动态渲染再节点上去
  wode(e){
       let value = e.target.value;
        this.setState({a: value})
  };
  hand(e){
       let value = e.target.value;
        this.setState({b: value})
           
  };
  tade(e){
       let value = e.target.value;
       this.setState({c: value})
           
  };
  nide(e){
       let value = e.target.value;
        this.setState({d: value})           
  };
  
  fn(){       
    //点击事件,然后拼接数据,最后通过AJAX发送待后台API地址,后台进行解析
      //对象值得方式
  var data = {name:this.state.a,pass:this.state.b,xingbie:this.state.c,tel:this.state.d}        
       var str = JSON.stringify(data); 
       document.write(str + "<br />")
  };
  render() {
    return (
      <div className="App">
            <div className="form-group">
            <label for="name">用户名</label>
            <input type="text" class="form-control"
                 placeholder="请输入名称"  value={this.state.a}  onChange={this.wode}/>
          </div>
           <div className="form-group">
            <label for="name">密码</label>
            <input type="text" class="form-control"
                 placeholder="请输入密码" value={this.state.b}  onChange={this.hand}/>
          </div>

          <div className="form-group">
             性别: <select value={this.state.c} onChange={this.tade}>
                      <option value="男">男</option>
                      <option value="女">女</option>
                     </select>
          </div>

           <div className="form-group">
            <label for="name">电话</label>
            <input type="text" class="form-control" 
                 placeholder="请输入电话" value={this.state.d}  onChange={this.nide}/>
          </div>

           <div className="form-group">
             <button type="button" className="btn btn-info" onClick={this.fn}>提交</button>
          </div>

      </div>
     
    );
  }
}

export default App;

this.wode = this.wode.bind(this);  react中事件的绑定写法,绑定在自己身上的意思。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐