首页 > 解决方案 > React - 如何从父组件中的函数制作组件?

问题描述

React 新手 - 我有一个组件 AddForm,如下所示:

class AddForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
    };
  }

  handleInput = event => {
    this.setState({ name: event.target.value });
  };

  logValue = () => {
    console.log(this.state.name)
    return <Display text={this.state.name} />
  };

  render() {
    return (
      <div>
        <input onChange={this.handleInput}
          placeholder="Type Here" type="text" />
        <button onClick={this.logValue}
          type="submit">Submit</button>        
      </div>
    )
  }
}

当用户单击“提交”按钮时,我希望它显示表单中的内容。我将值存储在 this.state.name 中的表单中,用于在表单内显示文本的组件如下所示:

class Display extends React.Component {
  render() {
    return (
      <h1>{this.props.text}</h1>
    )
  }
}

我知道我的 state.name 可以访问表单,因为我 console.logged 它。我只想知道为什么我在 AddForm 组件的 logValue 函数中的 return 语句没有创建一个新组件 Display,我怎样才能让它工作?

标签: javascriptreactjsreact-component

解决方案


单击按钮应该会导致状态更改,然后 render 方法会使用该状态更改来返回 Display 组件 - 类似于:

logValue = () => {
  this.setState({ showingName: !this.state.showingName });
}
render() {
  return (
    <div>
      {
        this.state.showingName ? <Display text={this.state.name} /> : null
      }
      <input onChange={this.handleInput}
        placeholder="Type Here" type="text" />
      <button onClick={this.logValue}
        type="submit">Submit</button>        
    </div>
  )
}

推荐阅读