可以在 style={} 中自我引用元素吗? - ReactJS
Possible to self refence element inside style={}? - ReactJS
是否可以在声明样式时引用按钮本身? style={this.current.disabled == true ? {...
<button
ref={createRef}
type='submit'
disabled={name === '' || category === '' || institute === '' || description === ''}
style={this.current.disabled == true ? { color: "red" } : { color: "yellow" }}
onClick={() => createChat()}
>Create</button>
谢谢
是的,这是可能的,但你必须这样使用
<button
ref={createRef}
type='submit'
disabled={name === '' || category === '' || institute === '' ||
description === ''}
style={{ color: this.current.disabled == true ? "red" : "yellow" }}
onClick={() => createChat()}
>Create</button>
这会起作用,即:
const disabled = name === '' || category === '' || institute === '' || description === '';
const buttonStyles = { color: "yellow" };
const disabledStyles = { color: "red" };
return <button
disabled={disabled}
style={{ ...buttonStyles, ...(disabled && disabledStyles) }}
>
Create
<button>
然而,你不能访问this
或底层元素——React函数组件没有this
,它的值将是未定义的。
您可以使用ref.current?.disabled
,但它在第一个运行上是未定义的,因此不推荐使用。
最好使用常规 css 或一些完整的 css-in-js 解决方案,因为您将能够访问 :disabled { }
伪选择器,像这样:
.my-button {
color: 'yellow';
}
.my-button:disabled {
color: 'red';
}
是否可以在声明样式时引用按钮本身? style={this.current.disabled == true ? {...
<button
ref={createRef}
type='submit'
disabled={name === '' || category === '' || institute === '' || description === ''}
style={this.current.disabled == true ? { color: "red" } : { color: "yellow" }}
onClick={() => createChat()}
>Create</button>
谢谢
是的,这是可能的,但你必须这样使用
<button
ref={createRef}
type='submit'
disabled={name === '' || category === '' || institute === '' ||
description === ''}
style={{ color: this.current.disabled == true ? "red" : "yellow" }}
onClick={() => createChat()}
>Create</button>
这会起作用,即:
const disabled = name === '' || category === '' || institute === '' || description === '';
const buttonStyles = { color: "yellow" };
const disabledStyles = { color: "red" };
return <button
disabled={disabled}
style={{ ...buttonStyles, ...(disabled && disabledStyles) }}
>
Create
<button>
然而,你不能访问this
或底层元素——React函数组件没有this
,它的值将是未定义的。
您可以使用ref.current?.disabled
,但它在第一个运行上是未定义的,因此不推荐使用。
最好使用常规 css 或一些完整的 css-in-js 解决方案,因为您将能够访问 :disabled { }
伪选择器,像这样:
.my-button {
color: 'yellow';
}
.my-button:disabled {
color: 'red';
}