这两个文本区域只是略有不同,我不明白为什么第二个不起作用。
const StyledTextarea = styled.textarea`
display: block;
font-size: 20px;
line-height: 40px;
min-height: 120px;
overflow: hidden;
padding: 0 7px;
margin: 0 0 30px;
resize: none;
width: 500px;
`;
const Label = styled.span`
color: ${props => props.green ? '#00BB00' : 'red'};
font-size: 1.5em;
`;
const App = () => {
return(
<div>
<Label green>✅ Textarea1 - Working </Label>
<Textarea1 />
<Label>❌ Textarea2 - Not working </Label>
<Textarea2 />
</div>
)
}
class Textarea1 extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda voluptas deleniti at, molestias in amet dolore voluptatem atque, modi minus ipsam dignissimos...',
scrollHeight: 0,
}
}
onChange(e) {
const t = e.target;
t.style.height = 'auto';
t.style.height = `${t.scrollHeight}px`;
this.setState({value: t.value});
}
render() {
return (
<StyledTextarea
value={this.state.value}
onChange={this.onChange.bind(this)}
/>
);
}
}
class Textarea2 extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda voluptas deleniti at, molestias in amet dolore voluptatem atque, modi minus ipsam dignissimos...',
scrollHeight: 0,
}
}
onChange(e) {
const bugger = e.target;
console.log('style.height before it is set to auto: ', bugger.style.height)
bugger.style.height = 'auto';
console.log('style.height after it is set to auto (obviously): ', bugger.style.height)
console.log('.scroll height: ', bugger.scrollHeight);
this.setState({
scrollHeight: bugger.scrollHeight,
value: bugger.value
});
}
render() {
return (
<StyledTextarea
style={{height: `${this.state.scrollHeight}px`}}
value={this.state.value}
onChange={this.onChange.bind(this)}
/>
);
}
}
两者都使用类似的方式来保持它们的高度与内容的高度同步。style.height
然而,第二个,我认为应该用新的(来自更新的状态)重新渲染,不应用新的样式。在控制台中查看有问题的值 - style.height 即使在分配新值之后仍保持“自动”。但是,如果您只按 Enter 和 Backspace ,它就可以工作。
什么是我不明白的?