【问题标题】:Render component number of times based on user input根据用户输入渲染组件的次数
【发布时间】:2017-12-02 03:41:56
【问题描述】:
我想根据用户输入呈现组件的次数。例如,我有一个问题,询问您要创建多少个框,旁边有一个文本框,您可以在其中提交一个数字。无论该数字是多少,我都想在屏幕上渲染该框的次数(假设我在另一个文件中创建了一个框)。我该怎么做呢?我是在我的 Box.js 文件(如下)还是我的组件所在的 App.js 文件中执行此操作?我需要一个简单而详细的解释,因为我是 React 新手。
我的代码使用 Bootstrap React:
const Box = (props) => {
return (
<div>
<Col xs={12} sm={8} md={8} lg={8} smOffset={2} mdOffset={2} lgOffset={2} >
<Panel bsClass="panel">
<Form horizontal>
<Row>
<Col componentClass={ControlLabel} lg={6}>
How many boxes do you want to create?
</Col>
<Col lg={4}>
<FormControl placeholder="Enter a number..." />
</Col>
<Col lg={2}>
<Button type="submit">
<FaArrowRight style={arrowStyle} />
</Button>
</Col>
</Row>
</Form>
</Panel>
</Col>
</div>
)
};
【问题讨论】:
标签:
reactjs
rendering
render
react-bootstrap
conditional-rendering
【解决方案1】:
您可能需要其他东西而不是功能组件。您只需将输入值存储在状态中并基于此进行渲染。一个非常简单的例子是:
const Box = React.createClass({
getInitialState: function() {
return {
numItems: null
};
},
render: function() {
let items = [];
for (let i = 0; i < this.state.numItems; i++) {
items.push(<p key={i}>Item {i}</p>);
}
return <div>
<input
type="number"
value={this.state.numItems}
onChange={this.handleValueChange} />
{items}
</div>;
},
handleValueChange: function(e) {
this.setState({
numItems: e.target.value
})
}
});
ReactDOM.render(<Box />, document.getElementById('root'));
<div id="root"></div>
<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>
【解决方案2】:
- 添加状态以计算框数
- 点击提交时更新计数
- 根据状态计数渲染框组件(设置状态后会自动发生)
盒子组件
class BoxComponent extends React.Component {
render() {
return (
<div>BOX</div>
);
}
}
获取用户输入组件
class Box extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
numberOfBoxes:0
};
}
updateBoxes(e) {
e.preventDefault();
this.setState({numberOfBoxes:e.target.value});
}
getBoxes(){
var rows=[];
for(var i=0;i<this.state.numberOfBoxes;i++ ){
rows.push(<BoxComponent/>);
}
return rows;
}
render() {
return (
<div>
<Col xs={12} sm={8} md={8} lg={8} smOffset={2} mdOffset={2} lgOffset={2} >
<Panel bsClass="panel">
<Form horizontal >
<Row>
<Col lg={6}>
How many boxes do you want to create?
</Col>
<Col lg={4}>
<FormControl onChange={this.updateBoxes.bind(this)} placeholder="Enter a number..." />
</Col>
<Col lg={2}>
<Button type="submit">
Submit
</Button>
</Col>
</Row>
</Form>
{this.getBoxes()}
</Panel>
</Col>
</div>
);
}
}
检查以下 jsfiddle
https://jsfiddle.net/madura/yeu699on/1/
请注意,在示例中,我在更改输入中的计数(onchange 事件)时添加到渲染框。不是表单提交事件。您可以将其添加到表单提交事件中,并在您的输入中有参考(查看反应参考以获取更多信息)。