reactjs - 使用 props 将状态钩子传递给另一个元素在 React 中不起作用?
问题描述
我有两个组件,一个应该具有显示和隐藏图标的状态。另一个应该至少在单击时显示该图标,因为默认状态是不显示任何内容,所以我尝试使用道具将 showIcon 函数向下传递给另一个元素,但它无法显示错误 showIcon is not a function
//Component A Row
import anItem from './anItem';
function Row(props) {
const [iconState, setIconState] = useState([]);
const icon = <FontAwesomeIcon icon={["fas", "check"]}/>
// from anItem component
const showIcon = ()=>{
setIconState([icon])
}
// from this component
const removeIcon = ()=>{
setIconState([])
}
// Pass the funtion down to the below componant so we can hide the element from there
let item = [<anItem icon=iconState showIcon={showIcon}/>]
return (
<li className="day-row check faderin" onClick={()=> reomveIcon()}>
// render all the items in the initial state
{item}
</li>
)
}
// Component B anItem
function anItem(props) {
return (
<div onClick={() =>{props.showIcon}>{porps.icon}</div>
)
}
export default anlItem
解决方案
在这里,我看到一些错字:
let item = [<anItem icon={iconState} showIcon={showIcon}/>] // add curly braces
确保正确定义以下函数(使用const关键字):
const showIcon = ()=> {
setIconState([icon])
}
const removeIcon = ()=> {
setIconState([])
}
我在您的anItem组件中还看到了另一个问题:
function anItem(props) {
return (
<div onClick={() => props.showIcon()}>{porps.icon}</div> // here onClick param
)
}
或者像这样:
function anItem(props) {
return (
<div onClick={props.showIcon}>{porps.icon}</div> // here onClick param
)
}
推荐阅读
- ios - 如何打开设备设置而不是应用程序特定设置?
- visual-studio-code - 尝试插入 char ](西班牙语布局键盘)做 ZoomIN
- jetty - 如何让 Jetty 读取新的 jetty-xxx.xml 文件
- ms-access - MS Access 中的慢速 Dlookup 调用
- c# - PowerPoint vb.net 参考当前幻灯片
- c - 宏定义“0000”的语法
- ms-access - 循环访问 Multiple Access 2016 表以基于每个表中的公共键创建连接字符串
- r - 如何将具有不同行/列顺序的两个等效数据帧排序为相同?(没有变量名,R 编程)
- javascript - 使用 JQuery SignalR 库进行身份验证
- java - 无法在开发本地机器的服务之间共享共享任务队列和数据存储区 - Google App Engine Java 标准环境