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

时间:2018-07-17 09:50:13

标签: javascript css reactjs styled-components

我正在使用组件库中的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 })} /> 组件。表单具有提交按钮的子组件。

const LoginForm = styled(Form)`
  Button_StyledButton{
    outline: black solid 10px;
  }
`

生成此html:

enter image description here

我想要定位按钮以为其设置样式。希望做这样的事情:

id    |    Name        |    Country
1     |    User1       |    India
2     |    User2       |    India
3     |    User3       |    India
4     |    User4       |    Australia
5     |    User5       |    Australia

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

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

1 个答案:

答案 0 :(得分:1)

由于您使用的不是公共图书馆,因此请确保您的图书馆可以通过className道具。

  

styled方法可以完全独立或完全适用   第三方组件,只要它们通过className   对其渲染子组件的支持,也应该通过它;以及   以此类推。最终,className必须向下传递到   实际的DOM节点才能使样式生效。

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

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

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

<form>
  <label>...</label>
  <input .../>
  <label>...</label>
  <input .../>
  <button>...</button>
</form>

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

const LoginForm = styled(Form)`
  button {
    outline: black solid 10px;
  }
`

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

如果未将className道具传递到正在使用的库中的组件树中,则需要提供包装器组件:

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