javascript-如何在React中传递带有事件处理函数的道具?

我正在尝试运行一个简单的应用程序,该应用程序以数组的形式呈现我一生获得的不同昵称.

我总共有两个组件,pushMe组件作为子按钮,nameFinder作为父按钮.我试图将我的display()方法作为onClick事件传递到pushMe按钮组件中,但该按钮不会呈现任何结果.我试图找出我所缺少的.

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import { PushMe } from "../components/PushMe";

class MyName extends React.Component {
  display() {
    //This will keep constant range from 1-10.
    var pickNickname = Math.floor(Math.random() * 11);
    let alias = ["Terrence", "T", "TT", "Trey"];
    let name;

    //This conditional statement will decide the name by determining a number from a variable.
    if (pickNickname <= 5) {
      name = <h1>Today, my name is {alias[0]}</h1>;
    } else if ((pickNickname = 6 || 7)) {
      name = <h1> Today, my name is {alias[1]}</h1>;
    } else if ((pickNickname = 8)) {
      name = <h1> Today, my name is {alias[2]}</h1>;
    } else {
      name = <h1> Today, my name is {alias[3]}</h1>;
    }
  }

  render() {
    return (
      <div className="myNameApp">
        <PushMe display={this.display} />
      </div>
    );
  }
}

ReactDOM.render(<MyName />, document.getElementById("root"));
import React from "react";

export class PushMe extends React.Component {
  render() {
    return <button onClick={this.props.display}> Push Me </button>;
  }
}

解决方法:

按下按钮后,您需要在render方法中渲染结果.将值推入状态并呈现内容.还要绑定显示方法以访问正确的上下文,例如

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import { PushMe } from "../components/PushMe";

class MyName extends React.Component {
  display = () => {
    //This will keep constant range from 1-10.
    var pickNickname = Math.floor(Math.random() * 11);
    let alias = ["Terrence", "T", "TT", "Trey"];
    let name;

    //This conditional statement will decide the name by determining a number from a variable.
    if (pickNickname <= 5) {
      name = alias[0];
    } else if ((pickNickname = 6 || 7)) {
      name = alias[1]
    } else if ((pickNickname = 8)) {
      name = alias[2]
    } else {
      name = alias[3]
    }
    this.setState({name});
  }

  render() {
    return (
      <div className="myNameApp">
         {this.state.name && <h1>Today, my name is {this.state.name}</h1>} 
        <PushMe display={this.display} />
      </div>
    );
  }
}

ReactDOM.render(<MyName />, document.getElementById("root"));
上一篇:javascript-确保组件只能是特定父组件的子组件


下一篇:javascript-如何为数组对象分配唯一索引值?