jsx 上的占位符错误

Error with place holder on jsx

我有一个简单的 React HTML 输入组件,当它用于不同的 sections/pages 时,我添加了一些道具来为其及其占位符设置样式。问题是有时我在编译时遇到错误(我们使用的是 nextjs)。 这是代码:

{placeHolderColor && (<style jsx>{`input::placeholder{color:${placeHolderColor}}`}</style>)}

基本上,我在 render 函数中使用 inline If with Logical && Operator 来检查道具 placeHolderColor 是否存在,并且如果存在,请添加样式标签。

我遇到的错误:

Warning: Unknown prop jsx on tag. Remove this prop from the element.

该错误仅在您重新加载页面时出现。如果您进行了更改并重新加载热代码 运行,则不会出现错误。不确定问题是文字中的 var、'::placeholder' 伪元素还是什么。代码仍然有效,如果定义了 placeHolderColor var,则应用样式。

我收到错误 Warning: Unknown prop 'jsx' on <style> tag. Remove this prop from the element. For details, see FB react-unknown-prop. 样式标签中的 jsx 属性 是什么意思?直接删除?

当我测试你的代码时,我遇到了同样的错误(也是在页面加载时)。之后,我在 ZEIT 的#next slack 频道 https://zeit.chat/ and he confirmed that the conditional use of <style jsx> tag is not supported. Here is his explanation https://github.com/zeit/styled-jsx/issues/233.

上与昵称 @g(在 github @giuseppeg)的风格化 jsx 开发人员进行了交谈

此外,在删除条件并像这样插入您的标签后:

<style jsx>{'input::placeholder{color:${placeHolderColor}}'}</style>

我遇到了这个错误:

Module build failed: SyntaxError: Expected placeHolderColor to not come from the closest scope. Styled JSX encourages the use of constants instead of props or dynamic values which are better set via inline styles or className toggling. See https://github.com/zeit/styled-jsx#dynamic-styles.

根据 https://github.com/zeit/styled-jsx#dynamic-styles, you basically should not add dynamic values into template literals inside <style jsx> tag (though you can put there constants and constant expressions starting from version 1.0.4 (see UPDATE at the bottom of the answer for details)). The reason behind the prohibition of using props/dynamic values, according to @giuseppeg comment in the slack thread https://zeit-community.slack.com/archives/C2U01UYEA/p1496928897076534 的建议,如下:"at the moment styled-jsx compiles and produces static code and therefore the hashes that make the final CSS unique won't change when the value of a variable like color changes"

因此,正如您从文档中看到的那样,建议通过内联样式或 class名称切换来使用动态值。不幸的是,无法通过 React 中的内联样式来设置伪元素(占位符等)的样式,因此如果您的可能颜色数量有限,则为每种颜色情况创建一个 class 并像这样使用它:

const InputWithColouredPlaceholder = props => (
  <div>
    <input
      placeholder="text"
      className={
        'placeholderColourClass' in props && props.placeholderColourClass
      }
    />
    <style jsx>{`
       .reddy::placeholder {
         color: red;
       }
       .greeny::placeholder {
         color: green;
       }
     `}</style>
  </div>
);

并将其渲染为 <InputWithColouredPlaceholder placeholderColourClass="reddy" />

虽然可能的颜色范围很大,但它会变得更加复杂。在这种情况下,我会建议在 ZEIT 的松弛 https://zeit.chat/.

的 #next 频道中征求建议

更新 在模板文字中使用常量和常量表达式应该在 styled-jsx 1.0.4 中有效(但 nextjs 目前依赖于 1.0.3,单独安装 styled-jsx 将无济于事,所以等待 nextjs 更新以支持 styled jsx 1.0。 4).这意味着任何未通过 props 传递且未在组件内部创建的常量都应该起作用(例如,您可以拥有一个带有颜色常量的 js 文件,并将它们导入到您的输入组件中)。但它不适合你的情况,因为你需要一种动态的方式。