我正在学习react-beautiful-dnd,我有这个组件:
function Card(props: CardProps) {
const { id } = props;
return (
<Draggable draggableId={String(id)} index={0}>
{provided => (
<div style={{backgroundColor: "brown"}}
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
>
<h2>Hello</h2>
</div>
)}
</Draggable>
);
}
当我按照他们的建议包含
{...provided.draggableProps}
时,它会删除样式标签。当我使用浏览器的检查器检查该元素时,它显示 style: ""
。我怎样才能防止这种情况发生?
draggableProps
包含 style
如果你想使用传入的样式但只更改一个属性,请更改组件 props 中样式的顺序
<div
{...provided.draggableProps}
{...provided.dragHandleProps}
style={{backgroundColor: "brown"}}
ref={provided.innerRef}
>
否则,从
draggableProps
中提取你需要的内容并忽略它附带的style
你可以这样使用:
function Card(props: CardProps) {
const { id } = props;
const style = {
...provided.draggableProps.style, // it needs to be firstly
// now put bellow your own styles
backgroundColor: "brown"
}
return (
<Draggable draggableId={String(id)} index={0}>
{provided => (
<div
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
style={style} // put the style here
>
<h2>Hello</h2>
</div>
)}
</Draggable>
);
}