因此,我正试图使用header.jsx中handleFontSize的onClick按钮来增加content.jsx文件中段落元素的字体大小。现在我的问题是App.jsx中的increaseFont函数无法正常工作。我每次点击按钮都只停留在12点。我希望它每次增加两个字体大小,这样它就会使fontSize变成12px(默认值(,然后是14px,然后是16px,以此类推
Header.jsx文件
import React from "react"; react
function Header ({ loggedIn, handleLoggedInClick, handleFontSize }) {
return (
<div>
<button onClick={handleLoggedInClick}>
{loggedIn ? "Log Out" : "Log In"}
</button>
<button onClick={handleFontSize}>
Increase
</button>
</div>
);
}
export default Header;
Content.jsx文件
import React from "react";
function Content ({ loggedIn, fontSize }) {
return loggedIn && <p style={{fontSize:{fontSize}}}>CONTENT</p>;
}
export default Content;
App.jsx文件
import React, { useState } from "react";
import Content from "./Content";
import Header from "./Header";
function App () {
const [loggedIn, setLoggedIn] = useState(false);
const [newFontSize, setFontSize] = useState(12);
const toggleLoggedIn = () => setLoggedIn(!loggedIn);
const increaseFont = () => setFontSize(newFontSize + 2)
return (
<div>
<Header loggedIn={loggedIn} handleLoggedInClick={toggleLoggedIn} />
<Content loggedIn={loggedIn} handleFontSize={increaseFont} fontSize={newFontSize} />
</div>
);
}
export default App;
试试这个:
App.js
import React, { useState } from "react";
import Content from "./Content";
import Header from "./Header";
function App () {
const [loggedIn, setLoggedIn] = useState(false);
const [newFontSize, setFontSize] = useState(12);
const toggleLoggedIn = () => setLoggedIn(!loggedIn);
const increaseFont = () => setFontSize(newFontSize + 2)
return (
<div>
<Header loggedIn={loggedIn} handleLoggedInClick={toggleLoggedIn} handleFontSize={increaseFont} />
<Content loggedIn={loggedIn} fontSize={newFontSize} />
</div>
);
}
export default App;
Content.jsx
import React from "react";
function Content ({ loggedIn, fontSize }) {
return loggedIn && <p style={{fontSize:fontSize}}>CONTENT</p>;
}
export default Content;
页眉.jsx
import React from "react"; react
function Header ({ loggedIn, handleLoggedInClick, handleFontSize }) {
return (
<div>
<button onClick={handleLoggedInClick}>
{loggedIn ? "Log Out" : "Log In"}
</button>
<button onClick={handleFontSize}>
Increase
</button>
</div>
);
}
export default Header;
试试这个,让我知道它是否有效,我只编辑了的前两个文件
您将handleFontSize传递给了错误的组件。应将其传递给标头组件
<div>
<Header loggedIn={loggedIn} handleLoggedInClick={toggleLoggedIn} handleFontSize={increaseFont} />
<Content loggedIn={loggedIn} fontSize={newFontSize} />
</div>