简体   繁体   中英

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

I am using a <Form/> component from a component library. The form has a child component for the submit button.

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

which generates this html:

在此处输入图片说明

I am wanting to target the button to style it. Was hoping to do something like this:

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

Essentially targeting the form and then the child button component.

Can this be done with styled components?

Since it's not a public library you're using, make sure your library avail you to pass className prop.

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.

If this condition is satisfied, you can take advantage of the styled(LoginForm) approach.

I don't know the DOM structure generated by your LoginForm , but you can effectively target the button by a normal css selector.

Let's assume the DOM structure is this:

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

Then you can target this button in the styled-components's styled method like this:

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

The selector really depends on the DOM structure, you need to adjust that to your needs.

If the className prop is not passed down the component tree in library you're using, you need to provide a wrapper component:

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 example: https://codesandbox.io/s/2w3owyjy2n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM