【问题标题】:Write a function in React js用 React js 写一个函数
【发布时间】:2018-10-24 12:13:25
【问题描述】:

您好,我是 React 和 js 的新手。

我正在尝试编写两个文本框,以便用户插入两个数字,然后单击“添加”按钮,他会得到结果。

我的建议是:

import React, { Component } from 'react';

export class Home extends Component {
displayName = Home.name

  render() {
    return (
        <div>
        <h1>Hello world! This is a new Web App</h1>

            <input type="text" name="" id="txt1" />
            +
            <input type="text" name="" id="txt1" />
            = <br/>
            <button onClick="add()">Add</button>

        </div>
      );
     }
    }

我认为还有一个函数 add() 将执行以下操作:

function add()
{
 var a = getElementById("txt1").value;
 var b = getElementById("txt2").value;
 alert(pardeInt(a)+parseInt(b));
}

如果有人可以编辑我建议的代码以使其正常工作,那就太好了。

提前致谢。

【问题讨论】:

  • 这看起来你还没有阅读关于如何在反应中使用事件处理程序和表单控件的第一件事。试试reactjs.org/docs/handling-events.html 和reactjs.org/docs/forms.html
  • 您只是在使用 react 来呈现 HTML 并使用 javascript。这与实际反应无关。请先阅读有关反应组件的更多信息。也许可以遵循一些教程?

标签: javascript reactjs


【解决方案1】:

首先你需要bind 函数到你的上下文。这可以通过

this.myFunction.bind()

或通过箭头函数(为你绑定函数)

那么你必须更新状态(当状态改变时会再次执行渲染):

import React, { Component } from 'react';

export class Home extends Component {
  state = { 
    result: 0,
    val1: 0,
    val2: 0,
  }

  handleChangeOne = (event) => {
    this.setState({val1: event.target.value});
  }
  
  handleChangeTwo = (event) => {
    this.setState({val2: event.target.value});
  }

  add = () =>
  {
   this.setState({
      result: parseInt(this.state.val1)+parseInt(this.state.val2)
      });
  }

  render() {
    return (
        <div>
        <h1>Hello world! This is the result: {this.state.result}</h1>

            <input onChange={this.handleChangeOne} type="text" />
            +
            <input type="text" onChange={this.handleChangeTwo} />
            = <br/>
            <button onClick={this.add}>Add</button>

        </div>
      );
     }
    }

避免直接访问 DOM,而是依赖本地状态。

【讨论】:

【解决方案2】:

您的代码只是告诉您没有 React.js 和 React Native 适当的知识。

当然你应该先看看 React.js 的基础,然后如果你想构建移动应用程序,React-Native 文档:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 2020-04-17
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多