【问题标题】:pass input value automatically to h1 in reactjspass input value automatically to h1 in reactjs
【发布时间】:2022-12-02 01:06:58
【问题描述】:

I am new to learning React. I need: entered text into the input to be automatically written in the H1 in screen.js file

Screen.js

export default function Screen(props){
    return (
      <div className="screen">
      <h1></h1>
    </div>
    );
  }
export default Screen;

Inputs.js

class Inputs extends React.Component {
  render() {
    return (
      <form>
        <input type="text" onChange={(e) => this.setState({ inputText: e.target.value })}/>
        <button type="button" onClick={() =>this.props.onAdd({inputText: this.state.inputText,})}>Send</button>
      </form>
    );
  }}
  export default Inputs;

App.js

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { inputText: '' };
    this.changeText = this.changeText.bind(this)
  }
  render() {
    return (
      <div>
        <h1>Hello world!</h1>
        <p>Start editing to see some magic happen :)</p>
        <Inputs onAdd={this.changeText} />
        <Screen onSave={this.changeText}/>
      </div>
    );
  }
  changeText(text){
    console.log(text)
  }
}
export default App;

【问题讨论】:

  • &lt;h1&gt;{this.state.inputText}&lt;/h1&gt;
  • This doesn't work. Changes must be in the screen.js file

标签: reactjs react-hooks


【解决方案1】:
export default function Screen(props){
    return (
      <div className="screen">
      <h1>{props.text}</h1>
    </div>
    );
  }
export default Screen;
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { inputText: '' };
    this.changeText = this.changeText.bind(this)
  }
  render() {
    return (
      <div>
        <h1>Hello world!</h1>
        <p>Start editing to see some magic happen :)</p>
        <Inputs onAdd={this.changeText} />
        <Screen text={this.state.inputText} onSave={this.changeText}/>
      </div>
    );
  }
  changeText(text){
    this.setState({ inputText: text })
  }
}
export default App;

【讨论】:

  • I got this error: Error in /turbo_modules/react-dom@18.1.0/cjs/react-dom.development.js (14757:9) Objects are not valid as a React child (found: object with keys {inputText}). If you meant to render a collection of children, use an array instead.
猜你喜欢
  • 2022-12-02
  • 2022-02-24
  • 2022-12-01
  • 2022-12-26
  • 2022-12-02
  • 2022-12-28
  • 2022-12-02
  • 1970-01-01
  • 2022-12-01
相关资源
最近更新 更多