根据常量显示单选按钮



我想显示许多等于const total_regions的单选按钮。我想给每一个不同的价值
E.g如果total_regions=5,则显示五个单选按钮,值为1-5。

import React from 'react';
const Test = props => {
const total_regions = (JSON.parse(JSON.stringify(props.test)).length); // gets the number of regions
return (
<ul>
{props.test.map(item => {
return <li>{item.length}</li>;
})}
</ul>                  
);
};
export default Test;

我试着摆弄道具,但我不知道如何为每个条目打印每个特定值的按钮。我可以把total_regions变成一个数组并使用映射吗

App.js:


import "bootstrap/dist/css/bootstrap.css";
import React from "react";
import ReactPlayer from 'react-player'
import LeftPane from "./components/LeftPane.js";
import Video from "./components/Video.js";
import Footer from "./components/Footer.js";
import Test from "./components/Test.js";
//import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { apiResponse: [] };
}
// Comunicate with API
callAPI() {
fetch("http://localhost:9000/IntensityAPI") //React app talks to API at this url
.then(res => res.json())
.then(res => this.setState({ apiResponse: res }));
}
componentWillMount() {
this.callAPI();
}
render() {
return (
<div className="App">
<div class="row fixed-top fixed-bottom no-gutters"  >
<div class="col-3 fixed-top fixed-bottom">
<LeftPane></LeftPane>
</div>
<div class="offset-md-3 fixed-top fixed-bottom" >
<Video></Video>
</div>
<div class=" col-3 fixed-bottom">
//  <Footer test = {this.state.apiResponse}/>
<Test test = {this.state.apiResponse}/>
</div>      
</div>
</div>
);
}
}
export default App;

您只需要在数据上循环并为数据中的每个项目返回一个单选按钮,我为您制作了一个沙盒示例。希望它能有所帮助:(

https://codesandbox.io/s/great-water-c0ihx?file=/src/App.js

您可以使用数组的index参数::map函数并映射到无线电类型的输入

{props.test.map((item, index) => {
return (
<label key={index}>
{item}
<input type="radio" value={index} />
</label>
);
})}

最新更新