这是可能的吗(标题)?我需要它,因为在css @media规则中需要更改一些元素的css。CSS部件工作。出现问题的原因是需要重新排列react组件。我有这些条件(他们两个)都通过了。它应该是,当窗口大小调整时,css得到应用,在获得窗口宽度后,组件在css更改后重新排列。我在构造函数中有这样的代码:
this.myInput = React.createRef();
还有这个:
componentDidMount () {
this.setState({
myWidth: this.state.myWidth=this.myInput.current.offsetWidth
});
}
在Render()中如下所示:
render(){
const btnText = this.state.erase ? "Populate" : "Erase" ;
const handleClick = e => this.fullScreen(e.target.id);
const EditorHead1 = <EditorHead id={"item1"} style={this.state.stilEditor} className={this.state.headEdKlasa} onClick={handleClick} title={this.state.attr}/>;
const PreviewHead1 = <PreviewHead id={"item2"} style={this.state.stilPreview} className={this.state.headViewKlasa} onClick={handleClick} title={this.state.attr}/>;
const BtnEraser1 = <BtnEraser id={"eraser"} onClick={this.eraseFields} type={"button"} className={"btn btn-danger btn-lg"} title={"Erase & populate both fields"} value={btnText}/>;
const Editor1 = <Editor id={"editor"} onChange={this.handleChange} className={this.state.editorKlasa} value={this.state.markdown} placeholder={"Enter ... some kind a text!? ..."} title={"This is rather obvious isnt it? Its editor window Sherlock :D"}/>;
const Preview1 = <Preview id={"preview"} className={this.state.previewKlasa} dangerouslySetInnerHTML={{__html: marked(this.state.markdown, { renderer: renderer })}} title={"Its a preview window, Sherlock ;)"}/>;
const Arrow1 = <Arrow id={"arrow"}/>;
if(this.state.myWidth<=768){
alert("Alternative");
alert(this.state.myWidth);
return (
<div id="inner2" ref={this.myInput} className="grid-container animated zoomIn" style={{height: this.state.inner2H}} onDoubleClick={this.inner2Height}>
{EditorHead1}
{Editor1}
{PreviewHead1}
{Preview1}
{BtnEraser1}
{Arrow1}
</div>
);
}
if(this.state.myWidth>768){
alert("Normal");
alert(this.state.myWidth);
return (
<div id="inner2" ref={this.myInput} className="grid-container animated zoomIn" style={{height: this.state.inner2H}} onDoubleClick={this.inner2Height}>
{EditorHead1}
{PreviewHead1}
{BtnEraser1}
{Editor1}
{Preview1}
{Arrow1}
</div>
);
}
}
目前,只有在调整大小后,刷新浏览器或再次“运行”代码时,重新排列才有效。
发布于 2018-09-03 06:03:55
应该侦听resize
事件,以便跟踪元素宽度的变化。对于可以经常触发的事件,最好去掉事件处理程序,这就是resize
:
import debounce from 'lodash.debounce';
...
myInput = React.createRef();
setMyWidth = () => {
this.setState({
myWidth: this.myInput.current.offsetWidth
});
}
onResize = debounce(this.setMyWidth, 100);
componentDidMount() {
this.setMyWidth();
window.addEventListener('resize', this.onResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize);
}
根据element offsetWidth
是什么,element引用可能是多余的,可以改为跟踪document.body.clientWidth
。
另外,this.state.myWidth=...
是一个错误,this.state
不应该直接在组件构造函数之外进行更改。
https://stackoverflow.com/questions/52141171
复制相似问题