在此帖子附带的代码段中,我尝试在用户点击input
时呈现div
代码。输入必须取代div,避免向用户提供组件更改的任何提示(如editablecell
属性)。
当渲染输入时,我会遇到元素高度的变化
const styles = {
cell: {
width: "200px",
border: "1px solid black",
lineHeight: "30px",
textAlign: "center",
verticalAlign: "middle"
},
input: {
width: "200px"
}
};
const text = "Click on me";
class App extends React.Component {
state = {
active: false
};
handleClick = () => {
this.setState(prevState => {
return {
active: !prevState.active
};
});
};
handleKeyPress = evt => {
if (evt.charCode === 13) {
this.setState(prevState => {
return {
active: !prevState.active
};
});
}
};
render() {
if (this.state.active) {
return (
<div>
<input
type="text"
style={styles.cell}
onKeyPress={this.handleKeyPress}
placeholder="Press ENTER when done"
/>
<p>Notice how the height is changing</p>
</div>
);
} else {
return (
<div>
<div style={styles.cell} onClick={this.handleClick}>
{text}
</div>
<p>Notice how the height is changing</p>
</div>
);
}
}
}
ReactDOM.render(<App />, document.getElementById("root"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
答案 0 :(得分:1)
您正在相互更改div
和input
,并且input
还有padding
,以便将height
增加1px 。将padding: 1px
添加到styles.cell
应修复。
答案 1 :(得分:1)
填充问题。设置一个值,它将按预期工作,看看这段代码。
const styles = {
cell: {
width: "200px",
border: "1px solid black",
lineHeight: "30px",
textAlign: "center",
verticalAlign: "middle",
padding: "0"
},
input: {
width: "200px"
}
};
const text = "Click on me";
class App extends React.Component {
state = {
active: false
};
handleClick = () => {
this.setState(prevState => {
return {
active: !prevState.active
};
});
};
handleKeyPress = evt => {
if (evt.charCode === 13) {
this.setState(prevState => {
return {
active: !prevState.active
};
});
}
};
render() {
if (this.state.active) {
return (
<div>
<input
type="text"
style={styles.cell}
onKeyPress={this.handleKeyPress}
placeholder="Press ENTER when done"
/>
<p>Notice how the height is changing</p>
</div>
);
} else {
return (
<div>
<div style={styles.cell} onClick={this.handleClick}>
{text}
</div>
<p>Notice how the height is not changing</p>
</div>
);
}
}
}
ReactDOM.render(<App />, document.getElementById("root"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;