reactjs - 如何在 React 中调用可重用组件中的函数
问题描述
嗨,我正在我的项目中处理一个 React 项目,一个按钮来了很多次。因此,我为 Button 创建了一个组件,并在获得按钮的地方重用该组件。现在的问题是,当我尝试将 onClick 函数应用于该 Button 组件时,我的函数不起作用,所以请帮我解决这个问题。
这是按钮组件 Button.js
import React from "react";
import "./Button.css";
const Button = () => {
return (
<div>
<button className="btn btn-primary">Show login button</button>
</div>
);
};
export default Button;
这是Button.css,我什么都没写
这是 App.js
import React, { useState } from "react";
import Button from "./Button/Button";
import "./App.css";
const App = () => {
const [hideForm, setHideForm] = useState(false);
const showLoginForm = () => {
setHideForm(true);
};
return (
<div className="container">
<div className="row justify-content-center">
<div className="col-4">
{hideForm ? (
<div className="loginform">
<form>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Enter email"
></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
placeholder="Enter password"
></input>
</div>
<button type="submit" className="btn btn-primary mt-3">
Submit
</button>
</form>
</div>
) : (
<div className="signupform">
<form>
<div className="form-group">
<label htmlFor="firstname">Firstname</label>
<input
type="text"
className="form-control"
id="firstname"
placeholder="Enter firstname"
></input>
</div>
<div className="form-group">
<label htmlFor="lastname">Lastname</label>
<input
type="text"
className="form-control"
id="lastname"
placeholder="Enter lastname"
></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Enter email"
></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
placeholder="Enter password"
></input>
</div>
<button type="submit" className="btn btn-primary mt-3">
Submit
</button>
</form>
</div>
)}
<div className="buttons mt-3">
<Button onClick={() => showLoginForm()}></Button>
</div>
</div>
</div>
</div>
);
};
export default App;
解决方案
const Button = ({handleClick}) => {
return (
<div>
<button onClick={handleClick} className='btn btn-primary'>Show login button</button>
</div>
)
}
像这样使用它:
<Button handleClick={()=>anyFunc()}/>
or
<Button handleclick={anyFunc}/>
``
推荐阅读
- jquery - 在 jQuery 中创建滑动导航栏
- jquery - 用于检查 div 没有类不工作的 JQuery 代码
- python - 什么是阻止同一行和列中的 2 个标签在 tkinter 中相互覆盖的好方法?
- python - 如何反向预测具有指定目标的特征值?
- java - JAVA pdfbox & GROOVY - 打开 PDF 时显示书签,setPageMode 不起作用
- java - System.LoadLibrary 在运行时或由用户控制
- python - 如何优化在 3 个重复维度上使用“itertools.product”的代码?执行超时
- javascript - 如何更改打字稿中的 CSS 类?
- google-apps-script - 如何修复“异常:在对象 SpreadsheetApp 上打开方法或属性时出现意外错误”?
- mysql - 如果我尝试通过 MySQL 存储过程从表单字段中插入超过 673 个字符的文本,文本就会消失