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

时间:2021-03-12 03:49:21

标签: javascript reactjs jsx react-props react-functional-component

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

这是我的代码。下面是我希望可以工作的伪代码。简而言之,我想动态设置一个道具名称,以便我可以让 hoverTxt 设置函数参数,因此如果我将 1 传递给 handleStyles 函数,它将返回 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;

1 个答案:

答案 0 :(得分:0)

Props 也是一个对象,您可以使用字符串访问对象键,例如

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