如何在引用自定义组件页面个性化自定义组件的样式
发布于 5 年前 作者 msun 13144 次浏览 来自 问答

RT,自定义组件是用shadow-root包装起来的,那么如何在引用页面定义组件的样式呢

9 回复

目前基础库的实现可以支持,不过__不推荐__这么做。

什么时候可以正式支持?@官方

实测在引用的页面里可以使用: 组件名 标签名 的形式。

比如自定义组件叫:btnex, btnex下有个button,以下样式可以作用到button上

btnex button{  height: 96rpx;}

请问这是一个普遍支持,还是少数机型上的个案

好的,感谢反馈。我们会尽快加入相关支持。

目前基础库版本 >= 1.9.90 已有 externalClasses 支持。正式文档尚未放出,你们可以先尝试下:

组件中:

Component({

externalClasses: [‘my-class’]

})

<view class=“my-class”> text </view>

组件外:

<my-component my-class=“the-class” />

.the-class {

background: red;

}

你好,现在暂不支持与样式class传递相关的特性,我们正在设计相关的接口。能否描述一下你具体的使用场景呢?

你可以给组件添加class,并用这个 class 去找 影子节点(shadow-root)下的元素进行设置,下边是demo

组件:

<view class="progress-bar" style="width: {{percentage}}%">{{percentage}}%</view>
<slot></slot>

样式:

.progress-container{
  height: 100%;
  padding: 0 5%;
  padding-top: 400rpx;
  box-sizing: border-box;
}
.progress-tip {
  text-align: center;
  margin-top: 70rpx;
  font-size: 18px;
}
:host{
  display: -webkit-box;
  display: flex;
  height: 1rem;
  overflow: hidden;
  font-size: 0.75rem;
  background-color: #e9ecef;
  border-radius: 0.25rem;
}
.progress-bar {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  flex-direction: column;
  -webkit-box-pack: center;
  justify-content: center;
  color: #fff;
  text-align: center;
  background-color: #1AAD19;
  transition: width 0.6s ease;
}
/*背景色*/
.bg-success{
  background-color: #28a745!important;
}
.bg-info{
  background-color: #17a2b8!important;
}
.bg-warning{
  background-color: #ffc107!important;
}
.bg-danger{
  background-color: #dc3545!important;
}
/*进度条动画*/
[@-webkit-keyframes](/user/-webkit-keyframes) progress-bar-stripes {
  from {
    background-position: 1rem 0;
  }
  to {
    background-position: 0 0;
  }
}
[@keyframes](/user/keyframes) progress-bar-stripes {
  from {
    background-position: 1rem 0;
  }
  to {
    background-position: 0 0;
  }
}
/*进度条背景色*/
.progress-bg-default {
  background-color: #007bff;
}
.progress-bg-success{
  background-color: #28a745!important;
}
.progress-bg-info{
  background-color: #17a2b8!important;
}
.progress-bg-warning{
  background-color: #ffc107!important;
}
.progress-bg-danger{
  background-color: #dc3545!important;
}
.progress-bar-striped view{
  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
  background-size: 1rem 1rem;
}
.progress-bar-animated view{
  -webkit-animation: progress-bar-stripes 1s linear infinite;
  animation: progress-bar-stripes 1s linear infinite;
}

引用:

<view class="progress-container">
  <better-progress class="progress-bar-striped progress-bar-animated" percentage="{{percentage}}"></better-progress>
  <view class="progress-tip">{{year}}年已经过去了{{percentage}}%</view>
</view>

就是开发了一个自定义组件,但是在不同页面中引入时,需要个性化该组件的部分样式

回到顶部