return 如何在 React 中设置常量

How return a setable const in React

我尝试编写一个函数 const,它可以 return 类似 const 的东西,低于目标。

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

但是我可以在其中注入一个可修改的变量,但我找不到如何在 jsx 中编写它。你可以在下面找到我的差异失败。可能吗?

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

最后我尝试做类似的事情:

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

尝试以下操作:

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

这是一个 example 的动作。

希望对您有所帮助。