繁体   English   中英

如何使用反应功能组件动态设置道具名称

[英]How to dynamically set prop names using react functional components

const handleStyle = () => {
           if (!props.hoverTxt) {
              return { display: "none" };
            } else {
              return {};
            }
          };    
          return (
            <div>
              <HeroAsideItems txt={props.hoverTxt} style={handleStyle()} />
            </div>
          );
        }
        
        export default HeroAsideCircles;

这是我的代码。 下面是我希望能工作的伪代码。 简而言之,我想动态设置一个道具名称,这样我就可以让 hoverTxt 设置 function 参数,所以如果我将 1 传递给 handleStyles function 它将返回 props.hovertxt1 或者如果我将参数设置为 6

    const handleStyle = (tEXTnUMBER) => {
    if (!props.hoverTxt + tEXTnUMBER) {
      return { display: "none" };
    } else {
      return {};
    }
  };



  return (
    <div>
      <HeroAsideItems txt={props.hoverTxt5} style={handleStyle(5)} />
    </div>
  );
}

export default HeroAsideCircles;

Props 也是一个 object 并且您可以使用字符串访问 object 键,例如

const obj = { name: 'Gwen' };

console.log(obj['name']);

基于此,您可以执行访问道具名称的确切方法

const handleStyle = (numberTxt) => {
  if (!props[`hoverTxt${numberTxt}`]) {
    return { display: "none" };
  } else {
    return {};
  }
};    

return (
  <div>
    <HeroAsideItems txt={props.hoverTxt5} style={handleStyle(5)} />
  </div>
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM