javascript - 当用户输入文本通过来自另一个组件的 props 时,在 React js 中不起作用

标签 javascript reactjs react-native components

我正在尝试使用 props 连接从另一个无状态组件传递数据的文本字段中输入的数据。不确定为什么它不起作用。

我创建了两个组件

  1. app.js 2.title.js 输入框输入的数据每次都需要拼接字符串,并使用props动态显示。

    App.js

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';
    import Home from './Home';
    import Title from './Title';
    
    class App extends Component {
    
      constructor(props)
      {
        super(props);
        this.state =
        {
          text : ' ',
          collection: []
        }
        this.eventHandler = this.eventHandler.bind(this);
        this.eventSubmit = this.eventSubmit.bind(this);
    
      }
    
      eventHandler(event)
    {
    
      this.setState(
        {text:event.target.value}
        )
    }
    
    eventSubmit(event)
    {
      this.setState(
        {collection:this.state.collection.concat(this.state.text)}
        )
    
    }
    
      render() {
       return (
          <div className="App">
          <input type="text" onChange ={this.eventHandler}  />
          <p> {this.state.text} </p>
          <input type="submit" onClick={this.eventSubmit} />  
          <title collection={this.state.collection} />
          </div>
        );
      }
    }
    export default App;
    

    标题.js

    import React from 'react';
    
    const title = (props) =>
    {
    
    return (
        <div>
        <h1> {this.props.collection.toString()} </h1>
        <h1> hello </h1>
        </div>
    );
    }
    export default title;
    

最佳答案

setState 是异步的,当你在其中使用 this.state 时,它​​可能不会重新渲染。改用 setState 中的函数:

eventSubmit(event) {
    this.setState((prevState, props) => ({
        collection: prevState.collection.concat(prevState.text)
    }));
}

参见 3. setState() 是异步的:https://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd

关于javascript - 当用户输入文本通过来自另一个组件的 props 时,在 React js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53527610/

相关文章:

javascript - 如何在 React 状态数组中不包含重复值?

javascript - 如何将 Bootstrap 5 与 Next.js 一起使用?

android - react-native-vector-icons/羽毛图标不显示

typescript - 在通用组件中使用时注释 useNavigation 类型

php - 将 JavaScript 结果存储在 Php 变量中

javascript - 使用 jQuery 检查是否需要输入字段

javascript - 在 Google Apps 脚本中调用函数

javascript - 将 li 附加到 ul 时遇到问题

javascript - 导入和导出 es6 类

android - react-native-keyboard-aware-scroll-view 中平台之间的不同行为