关于javascript:是否可以从库中定位样式化组件的子组件?

Is it possible to target a child component of styled component from a library?

我正在使用组件库中的<Form/>组件。表单具有"提交"按钮的子组件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const loginForm = [
  {
    label:"Username",
    required: true,
    type:"text"
  },
  {
    label:"Password",
    required: true,
    type:"password"
  }
]

<LoginForm
  width={{ xs: 12, md: 4 }}
  autoComplete={false}
  buttonDisabled={buttonDisabled}
  buttonLabel="LOGIN"
  fields={loginForm}
  onChange={this.onChange}
  onSubmit={data => login({ variables: data })}
/>

生成此html:

enter

1
2
3
4
5
const LoginForm = styled(Form)`
  Button_StyledButton{
    outline: black solid 10px;
  }
`

本质上是针对表单,然后是子按钮组件。

这可以通过样式化组件来完成吗?


由于您使用的不是公共图书馆,请确保您的图书馆可以帮助您传递className属性。

The styled method works perfectly on all of your own or any
third-party components as well, as long as they pass the className
prop to their rendered sub-components, which should pass it too, and
so on. Ultimately, the className must be passed down the line to an
actual DOM node for the styling to take any effect.

如果满足此条件,则可以利用styled(LoginForm)方法。

我不知道您的LoginForm生成的DOM结构,但是您可以通过普通的CSS选择器有效地定位按钮。

让我们假设DOM结构是这样的:

1
2
3
4
5
6
7
<form>
  <label>...</label>
  <input .../>
  <label>...</label>
  <input .../>
  <button>...</button>
</form>

然后,您可以像这样在样式化组件的styled方法中定位此按钮:

1
2
3
4
5
const LoginForm = styled(Form)`
  button {
    outline: black solid 10px;
  }
`

选择器实际上取决于DOM结构,您需要根据需要进行调整。

如果className道具未沿您使用的库中的组件树传递,则需要提供package器组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const Wrapper = styled.div`
  button {
    outline: black solid 10px;
  }
`
<Wrapper>
  <LoginForm
    width={{ xs: 12, md: 4 }}
    autoComplete={false}
    buttonDisabled={buttonDisabled}
    buttonLabel="LOGIN"
    fields={loginForm}
    onChange={this.onChange}
    onSubmit={data => login({ variables: data })}
  />
</Wrapper>

CodeSandbox示例:https://codesandbox.io/s/2w3owyjy2n