我正在做一个React项目,因为我有App.js,这是Parent组件。而且我有
另一个组件是Child.js,此组件是App.js的子组件。
我Child.js我有一个按钮,我编写了一个函数,即有人单击
按钮的背景颜色将改变。我已经在Child.js组件中编写并应用了
该按钮。现在,我必须更改Child.js Button Text的颜色,为此我写了一个
App.js中的函数,我正在尝试将该函数传递给Child.js。但是我无法获得
输出,请帮助我获取输出。
这是App.js
MessagingCenter.Subscribe<HomePage>(this, "Shutdown", (sender) =>
{
OnShutdown();
});
这是Child.js
import React, { useState } from 'react';
import './App.css';
import Child from './Child/Child';
function App() {
const [textColor, setTextColor] = useState('');
const changeTextColor = () => {
setTextColor('yellow')
}
return (
<div className="App">
<Child Fun={changeTextColor}></Child>
</div>
);
}
export default App;
答案 0 :(得分:1)
您没有在任何地方使用textColor
状态。我的猜测是您想以这种方式使用它:
const [textColor, setTextColor] = useState('white');
<Child textColor={textColor} Fun={changeTextColor}></Child>
并在子组件中:
<div>
<button className='btn btn-primary'
style={{background: bg, color: props.textColor }}
onClick={() => {color(); props.Fun()}}>Child Button</button>
</div>
答案 1 :(得分:1)
您必须将有关颜色变化的道具传递给子组件。我了解到您的情况,没有向孩子发送任何道具。
https://codesandbox.io/s/access-child-component-method-react-hook-olmco?file=/src/Child.js:0-445
import React, { useState } from "react";
import Child from "./Child";
function Parent() {
const [textColor, setTextColor] = useState("");
function changeTextColor() {
setTextColor("blue");
}
return (
<div className="App">
<Child Fun={changeTextColor} textColor={textColor} />
</div>
);
}
export default Parent;
import React, { useState } from "react";
const Child = props => {
const [bg, setBg] = useState("");
const color = () => {
setBg("red");
};
return (
<div>
<button
className="btn btn-primary"
style={{ color: props.textColor, background: bg, }}
onClick={() => {
color();
props.Fun();
}}
>
Child Button
</button>
</div>
);
};
export default Child;
答案 2 :(得分:0)
您正在传递并正确使用您的功能。如果您将textColor
登录到App.js
,您会看到颜色实际上已经更新。
问题是,您当前不在任何地方使用textColor
变量,因此看不到更改。像往常一样将textColor
传递给您的孩子,并在某个地方使用它来直观地看到变化。
(注意:在这种情况下,我会将您的textColor
状态保留在子组件中,而不是App
)