使用props传递状态钩子到另一个元素在React中不工作?



我有两个组件,一个应该有显示和隐藏图标的状态。另一个应该至少在点击时显示图标,因为默认状态是不显示任何东西,所以我试图通过使用props将showIcon函数传递给另一个元素,但它没有显示错误showIcon不是一个函数

//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
)
}

最新更新