[英]React.js style mutation error…?
这就是我正在使用的:
反应:15.6.1
触发onChange时发生错误。
import React, { Component } from 'react';
var defaults = {
text: {
placeholder: '',
label: ''
},
style: {
wrapper: {
display: 'block',
padding: '9px 0'
},
label: {
display: 'block',
padding: '0px 8px 4px',
color: require('macros').theme.text.info
},
input: {
display: 'block',
position: 'relative',
boxSizing: 'border-box',
border: 0,
outline: 0,
// border: `1px solid ${ require('macros').theme['text field'].border }`,
width: '100%',
padding: '12px 6px',
fontSize: '16px',
background: require('macros').theme['text field'].background,
color: require('macros').theme.text.info
},
active: {
input: require('macros').theme['text field'].active.background
}
},
type: 'text',
onChange: function() {}
};
export default class Nav extends Component {
constructor(props) {
super(props)
var component = this;
component.state = require('venatici').object.combine(defaults, component.props);
component.onChange = component.onChange.bind(this);
}
onChange(event) {
var component = this;
component.state.onChange(event.target.value);
component.state.style.input.background = '#494949';
component.forceUpdate();
}
render() {
var component = this;
return (
<text-field
ref='outer'
style={ component.state.style.wrapper }
>
<label style={ component.state.style.label }>{ component.state.text.label }</label>
<input
name={ component.state.type }
type={ component.state.type }
style={ component.state.style.input }
placeholder={ component.state.text.placeholder }
onChange={ component.onChange }
></input>
</text-field>
);
}
componentDidMount() {
}
}
警告: input
已传递了先前已更改的样式对象。 不推荐使用变异style
。 考虑事先克隆它。 检查Nav
的render
。 上一样式:{显示:“块”,位置:“相对”,框大小:“边框”,边框:0,轮廓:0,宽度:“ 100%”,填充:“ 12px 6px”,fontSize:“ 16px ”,背景:“#333”,颜色:“#eee”}。 突变样式:{显示:“块”,位置:“相对”,boxSizing:“边框”,边框:0,轮廓:0,宽度:“ 100%”,填充:“ 12px 6px”,fontSize:“ 16px ”,背景:“#494949”,颜色:“#eee”}。
任何帮助将不胜感激。 谢谢!
代替
component.state.style.input.background = '#494949';
component.forceUpdate();
做
const inputStyles = Object.assign({}, component.state.style.input, { background: '#494949' });
const styles = Object.assign({}, component.state.style, { input: inputStyles });
component.setState({ style: styles });
component.state.style.input.background = '#494949';
component.forceUpdate();
这部分是非常不正确的。
首先,永远不要直接更改组件状态中的任何值。 允许您更改状态的唯一且唯一的方法是使用setState
挂钩。
其次, forceUpdate
是极端情况的挂钩。 通常,如果发现需要使用它,则意味着代码中存在严重问题。 在这种情况下,这是因为您不应该使用setState
。 setState
将始终使组件重新评估其render方法并确定是否需要更新。
最后,虽然不是“错误”,但没有理由使用赋值component = this
。 如果您所处的上下文中this
关键字不再是组件,则再次说明您的代码结构有问题。
您可以将以下两行替换为:
this.setState((oldState) => {
return {
...oldState,
style: {
...oldState.style,
input: {
...oldState.style.input,
background: '#494949'
}
}
}
});
如果您不使用这种深层嵌套的状态模型,则可能会更加干净,但这种方式仍然很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.