const
handleClick
= () => {
ref.
current
.
style
.
backgroundColor
=
'salmon'
;
ref.
current
.
style
.
color
=
'white'
;
ref.
current
.
style
.
padding
=
'2rem'
;
ref.
current
.
style
.
width
=
'300px'
;
return
(
<
button
onClick
=
{handleClick}
>
Change styles
</
button
>
<
div
ref
=
{ref}
>
Some content here
</
div
>
</
div
>
当我们将 ref prop 传递给元素时,例如
<div ref={myRef} />
,React将ref对象的
.current
属性设置为对应的DOM节点。
我们可以访问元素的 style 属性来获取元素样式的对象。
style 属性可用于在 DOM 元素上设置样式或读取元素的现有样式。
请注意
,多词属性名称是驼峰式的,例如
backgroundColor
。
在 React 中使用 ref 来切换元素的样式:
在元素上设置 ref 属性。
检查元素上是否存在特定样式。
如果设置了样式,请将其删除。否则在元素上设置样式。
import
{useRef}
from
'react'
;
const
App
= () => {
const
ref =
useRef
();
const
handleClick
= () => {
if
(ref.
current
.
style
.
backgroundColor
) {
ref.
current
.
style
.
backgroundColor
=
''
;
ref.
current
.
style
.
color
=
''
;
}
else
{
ref.
current
.
style
.
backgroundColor
=
'salmon'
;
ref.
current
.
style
.
color
=
'white'
;
return
(
<
button
onClick
=
{handleClick}
>
Change styles
</
button
>
<
div
ref
=
{ref}
>
Some content here
</
div
>
</
div
>
export
default
App
;
React 工厂方法——createFactory使用详解
Webpack打包ES6和CommonJs混合React
React 中 Attempted import error 'X' is not exported from 错误
React 错误 Component definition is missing display name 修复
解决 React Hook 'useState' is called conditionally 错误