首页 > 解决方案 > ReactJS - 如何设置父级样式?

问题描述

我想将样式放在“Forms_formline__3DRaL”div 上(见下文)这个 div 来自一个组件;并且似乎这种样式应用于 input ,而不是其父 div。我如何通过 reactjs 为父 div 定义样式“display:none”?

这是我的代码:

<MyInput
  style={{
    display:
      type == 1
        ? 'none'
        : 'block',
  }}
  id="name"
  type="text"
  label={t('elevation_loss')}
  value="name"
/>

这是我的 chrome 源代码中的结果:

<div class="Forms_formline__3DRaL">
    <label for="name">Name *</label>
    <input type="text" id="name" value="" style="display: none;">
</div>

标签: cssreactjsnext.js

解决方案


你可以尝试做这样的事情

import { CSSProperties, FC } from 'react';

export const MyInput: FC<{
    styleOverrides: {
        container: CSSProperties;
    };
    id: string;
    type: string;
    label: string;
}> = ({ styleOverrides }) => {
    return (
        <>
            <div className="Forms_formline__3DRaL" style={styleOverrides.container}>
                ...
            </div>
        </>
    );
};

推荐阅读