首页 > 解决方案 > 当用户输入通过来自另一个组件的道具的文本时,在反应 js 中不起作用

问题描述

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

我创建了两个组件

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

    应用程序.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;
    

标签: javascriptreactjsreact-nativecomponents

解决方案


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


推荐阅读