gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:27:43 25 4
gpt4 key购买 nike

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

我总共有两个组件,作为子按钮的 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>;
}
}

最佳答案

您需要在按下按钮后在渲染方法中渲染结果。推送状态中的值并呈现内容。还绑定(bind)显示方法以访问正确的上下文,如

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 - 如何在 React 中传递带有事件处理函数的 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54657088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com