javascript - React:内联样式未应用于子组件
问题描述
目标:我有一个 Main 组件和一个 Textarea 组件。给定textarea的scrollHeight,我想动态调整textarea及其父容器的大小。此外,我还有一个 Button 组件,它是 Main 的子组件,它将清除 textarea 中的文本,但这不是我最关心的问题。只是想添加更多上下文。
问题:目前,主要组件反映了正确的初始状态值和更改后的状态值。但是,当我尝试将更新的 parentHeight 和 textareaHeight 值向下传递给子组件、转换为字符串并在样式属性中设置 CSS 属性时,就会发生故障。
顺便说一句,我已经包含了注释代码块来说明我已经走了一些其他方向。
import Textarea from '../textareas/Textarea';
import Buttons from '../button-group/Buttons';
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
textareaIsEmpty: true,
textareaHeight: 'auto',
parentHeight: 'auto',
}
this.handleChange = this.handleChange.bind(this);
}
handleChange = (textareaHeight, parentHeight) => {
this.setState({
parentHeight: parentHeight,
textareaHeight: textareaHeight,
});
}
handleClick = () => {
this.setState({
textIsCleared: false,
});
console.log(this.textIsCleared);
}
render() {
return (
<section className="section">
<Textarea handleChange={this.handleChange} />
<Buttons onClick={() => this.handleClick()} />
<Textarea handleChange={this.handleChange} />
</section>
);
}
}
export default class Textarea extends React.Component {
constructor(props) {
super(props);
// this.state = {
// parentStyle: {
// minHeight: this.props.parentHeight,
// },
// textareaStyle: {
// height: this.props.textareaHeight,
// },
// }
this.parentStyle = {
minHeight: `${this.props.parentHeight}px`,
}
this.textareaStyle = {
height: `${this.props.textareaHeight}px`,
}
this.onChange = this.onChange.bind(this);
}
onChange = (e) => {
const newTextareaHeight = e.target.scrollHeight;
const newParentHeight = e.target.parentElement.scrollHeight;
this.props.handleChange(newTextareaHeight, newParentHeight);
this.setStyles();
}
setStyles = () => {
// this.setState({
// parentStyle: {
// ...this.state.parentStyle,
// minHeight: `${this.props.parentHeight}px`,
// },
// textareaStyle: {
// ...this.state.textareaStyle,
// height: `${this.props.textareaHeight}px`,
// },
// })
}
render() {
const parentStyle = `${this.props.parentHeight}px`;
const textareaStyle = `${this.props.textareaHeight}px`;
return (
<div className="content_wrap" style={{minHeight: parentStyle}}>
<textarea
className="content_textarea"
onChange={this.onChange}
rows={1}
style={{height: textareaStyle}}
/>
</div>
)
}
}
解决方案
可能问题在于,在Textarea
您尝试从 props 读取parentHeight
和textareaHeight
值的组件中,但在Main
组件中您没有将这些 props 传递给 child Textarea
。
推荐阅读
- javascript - 运行 npm start 时出现 Webpack css loader 错误
- azure-active-directory - MS Azure AD OWIN 在短时间内重新进行身份验证
- rest - Salesforce Rest API - Upsert 数组记录
- php - 将导入的带有矩阵表的 Excel 转置到 Laravel
- python - 需要和提供 Python 算法
- c# - 与剧作家一起下载进度
- c++ - 如何在关键字 this 上调用重载 () 运算符?
- reactjs - 反应上下文 - 状态值不正确
- php - PHP爆炸成数组,但只在一个字符后面
- android-studio - 如何使用 burpsuite 配置 android studio 模拟器 pixel 4 api 28