简体   繁体   English

如何在 React 中返回可设置的常量

[英]How return a setable const in React

I try to write a function const who can return something like a const, bellow the goal.我尝试编写一个函数 const ,它可以返回类似于 const 的东西,低于目标。

const button_style = {
  width: "100px",
  height: "100px",
}

but where I can inject a modificable variable, but I don't find how write that in jsx.但是我可以在哪里注入一个可修改的变量,但是我没有找到如何在 jsx 中编写它。 You can find bellow my differents fails.你会发现我的不同之处失败了。 Is it possible ?是否可以 ?

const set_button_style = () => {
  let w = 100
  let h = 100
  return ({ width: `${w}px`, height: `${h}px` });
}
const set_button_style = () => {
  let w = 100
  let h = 100
  return <div>{{ width: `${w}px`, height: `${h}px` }}</div>
}

at the end I try to do something like that :最后我尝试做这样的事情:

function Cell({ children }) {
  return (
    <div>
      <button
        onClick={() => toggle_cell()}
        className="cell"
        // style={button_style}
        style={set_button_style}
        // style={{ width: `${w}px`, height: `${h}px` }}
      >
        {<Img fluid={children.childImageSharp.fluid} />}
      </button>
    </div>
  )
}

Try the following:请尝试以下操作:

const set_button_style = () => {
  let w = 100
  let h = 100
  return { width: `${w}px`, height: `${h}px` };
};
function Cell({ children }) {
  const buttonStyles = set_button_style();
  return (
    <div>
      <button
        onClick={() => toggle_cell()}
        className="cell"
        style={set_button_style}
      >
        {<Img fluid={children.childImageSharp.fluid} />}
      </button>
    </div>
  )
}

Here is an example in action.这是一个实际的例子

Hopefully that helps.希望这有帮助。

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

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