You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中SlateJS编辑器设置图片固定宽高的问题

在React项目的SlateJS编辑器中插入固定宽高图片的问题

我在React项目中使用SlateJS编辑器,想要插入一张固定宽高(600px/200px)的图片。目前点击按钮插入图片的代码如下:

const image = {
    type: 'image',
    url: 'https://images.unsplash.com/photo-1706562018252-5ce3eadb2288?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=100&ixid=MnwxfDB8MXxyYW5kb218MHx8fHx8fHx8MTcwNzIzODM1MA&ixlib=rb-4.0.3&q=80&w=600',
    children: [{ text: '' }]
};
Transforms.insertNodes(editor, image);

我曾尝试直接在image常量中指定width和height属性,但未生效:

const image = {
    type: 'image',
    url: 'https://images.unsplash.com/photo-1706562018252-5ce3eadb2288?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=100&ixid=MnwxfDB8MXxyYW5kb218MHx8fHx8fHx8MTcwNzIzODM1MA&ixlib=rb-4.0.3&q=80&w=600',
    children: [{ text: '' }],
    width: "600px",
    heigth: "200px"
};
Transforms.insertNodes(editor, image);

我还尝试添加style属性,但依旧无效:

const image = {
    type: 'image',
    url: 'https://images.unsplash.com/photo-1706562018252-5ce3eadb2288?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=100&ixid=MnwxfDB8MXxyYW5kb218MHx8fHx8fHx8MTcwNzIzODM1MA&ixlib=rb-4.0.3&q=80&w=600',
    children: [{ text: '' }],
    style: {
        width: "600px",
        heigth: "200px"
    }
};
Transforms.insertNodes(editor, image);

解决方案

SlateJS不会自动将节点属性映射到DOM样式,需要在自定义的图片渲染组件中读取节点属性并应用到img标签上,同时注意修正拼写错误:

  1. 定义图片渲染组件
const ImageElement = ({ attributes, children, element }) => {
  return (
    <div {...attributes}>
      <img
        src={element.url}
        style={{
          width: element.width || 'auto',
          height: element.height || 'auto'
        }}
        alt=""
      />
      {children}
    </div>
  );
};
  1. 注册渲染组件到编辑器
const renderElement = (props) => {
  switch (props.element.type) {
    case 'image':
      return <ImageElement {...props} />;
    default:
      return <DefaultElement {...props} />;
  }
};
  1. 修正插入代码的拼写错误
const image = {
    type: 'image',
    url: 'https://images.unsplash.com/photo-1706562018252-5ce3eadb2288?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=100&ixid=MnwxfDB8MXxyYW5kb218MHx8fHx8fHx8MTcwNzIzODM1MA&ixlib=rb-4.0.3&q=80&w=600',
    children: [{ text: '' }],
    width: "600px",
    height: "200px" // 修正heigth为height
};
Transforms.insertNodes(editor, image);

这样图片就能按照指定的600px宽、200px高渲染了。


内容的提问来源于stack exchange,提问作者Fabrizio Greco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 20:36:08