首页 > 解决方案 > 使用 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

标签: reactjs

解决方案


在这里,我看到一些错字:

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

推荐阅读