WordPress カスタムブロック開発関連メモ。
RangeControl などで指定された数値を元に、例えば CSS の opacity プロパティ用の値を取得すると、ブロックエディター上ではうまく不透明度が反映されますが、実際にフロントエンドのページで確認してみると反映されていません。
save 関数例
export const save = props => {
const {
attributes,
} = props
const {
text,
opacity
} = attributes
// インラインスタイル用の CSS
const style = {
'--bg-opacity' : opacity
}
// インラインスタイルをセット
const blockProps = useBlockProps.save( {
style: style
} )
return
<div { ...blockProps }>
<div className="wrapper__inner">
<RichText.Content
tagName='span'
value={ text }
/>
</div>
</div>
}
出力されたブロックの要素を確認してみると、ブロックのラッパー要素にインラインスタイルで挿入したはずの opacity プロパティの数値に「px」という単位名が勝手に追加されています。
ブロックの実際の出力内容
<div class="wp-block-my-block" style="--bg-opacity:0.5px"> <span>てきすと</span> </div>
React のドキュメントにはこうありました。
React will automatically append a “px” suffix to certain numeric inline style properties. If you want to use units other than “px”, specify the value as a string with the desired unit.
https://reactjs.org/
つまり、特定の数値のインラインスタイルプロパティは、React で自動的に「px」接尾辞を付けるという仕様のようです。
これを回避するには、対象の変数は数値ではなく文字列として処理します。
文字列として値をセット
const style = {
'--bg-opacity' : `${ opacity }`
}
