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

React父组件未更新:react-to-print无法获取textarea新样式问题

解决react-to-print打印时textarea高度不更新的问题

核心问题原因

直接通过ref修改DOM的样式不会触发React重渲染,而react-to-print是基于克隆React渲染后的DOM生成打印内容的,原DOM上的样式变更无法同步到克隆的打印DOM中。需要将textarea的高度维护为组件状态的一部分,确保React渲染时将最新高度作为内联样式应用。

修改方案

1. 重构子组件,将高度维护到state中

class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
        this.noteTextRef = React.createRef();
        this.state = {
            textareaHeight: 'inherit'
        };
    }

    // 组件挂载后初始化高度
    componentDidMount() {
        this.updateTextareaHeight();
    }

    // props更新时重新计算高度(根据实际业务判断触发条件)
    componentDidUpdate(prevProps) {
        if (prevProps.note !== this.props.note) {
            this.updateTextareaHeight();
        }
    }

    // 计算并更新textarea高度的通用方法
    updateTextareaHeight = () => {
        if (!this.noteTextRef.current) return;
        
        // 先重置高度,保证scrollHeight计算准确
        this.noteTextRef.current.style.height = "inherit";
        const scrollHeight = this.noteTextRef.current.scrollHeight;
        this.setState({ textareaHeight: `${scrollHeight}px` });
    };

    handleUpdate = (e) => {
        // 处理输入逻辑
        // ...
        // 输入变更时同步更新高度
        this.updateTextareaHeight();
    };

    render() {
        return (
            <textarea
                cols="50"
                ref={this.noteTextRef}
                className="form-control visit-notes"
                id="desc"
                name="note"
                onChange={this.handleUpdate}
                value={this.props.note || 'some value'}
                // 将state中的高度作为内联样式绑定
                style={{ height: this.state.textareaHeight }}
            />
        );
    }
}
export default ChildComponent;

2. 确保父组件正确配置react-to-print

父组件需要通过ref获取子组件实例,让react-to-print基于最新渲染的组件生成打印内容:

import ReactToPrint from 'react-to-print';

const PrintComponent = (props) => {
    const childComponentRef = React.useRef();

    return (
        <>
            <ChildComponent ref={childComponentRef} {...props} />
            <ReactToPrint
                trigger={() => <button>触发打印</button>}
                content={() => childComponentRef.current}
            />
        </>
    );
}
export default PrintComponent;

关键说明

  • 废弃UNSAFE_componentWillReceiveProps:该生命周期已被React标记为不安全,改用componentDidUpdate处理props变更后的逻辑。
  • 状态驱动样式:通过state维护高度,确保React每次渲染都能将最新高度应用到textarea,react-to-print克隆的DOM会同步拿到这一最新样式。
  • 实时更新:在输入变更(handleUpdate)、组件挂载、props更新时都调用高度计算方法,保证UI和打印内容的高度一致。

内容的提问来源于stack exchange,提问作者Rajesh Barik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:10:33