我有一个 ButtonGroup 作为导航栏中的单选按钮。我想返回某个页面中所选按钮的值。我没有太多 React 经验,我有点迷失。
我有两个 .js 文件:sidebar.js 和 page.js。
侧边栏.js:
import React, { Component } from 'react';
import classNames from 'classnames';
import history from '../../core/history';
import {
Radio,
ButtonGroup,
Button } from 'react-bootstrap';
class Sidebar extends Component {
_onOptionChange(option) {
this.setState({
option: option
});
}
render() {
return (
<div>
...
...
...
<li>
<ButtonGroup vertical block data-toggle="buttons">
<Button className="btn btn-block" onClick={this._onOptionChange.bind(this, 'optionA')} active={this.state.option === 'optionA'}>Option A</Button>
<Button className="btn btn-block" onClick={this._onOptionChange.bind(this, 'optionB')} active={this.state.option === 'optionB'}>Option B</Button>
<Button className="btn btn-block" onClick={this._onOptionChange.bind(this, 'optionC')} active={this.state.option === 'optionC'}>Option C</Button>
</ButtonGroup>
</li>
...
...
...
</div>
);
}
}
export default Sidebar;
page.js:
import React, { PropTypes } from 'react';
import { PageHeader } from 'react-bootstrap';
const title = 'Page';
function displayPage(props, context) {
context.setTitle(title);
return (
<div>
<div className="row">
<div className="col-lg-12">
<PageHeader>Title</PageHeader>
</div>
<div className="col-lg-6">
{ value of selected radio button }
</div>
</div>
</div>
);
}
displayPage.contextTypes = { setTitle: PropTypes.func.isRequired };
export default displayPage;
如何返回所选值? 谢谢!
最佳答案
来自React docs :
The state contains data specific to this component that may change over time.
在您的 Sidebar
中组件中,单击按钮将通过调用 this.setState({ ... })
更改侧边栏的内部状态.
考虑使用 props 设计组件时:
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
所以,就你而言 - 我会想到 Sidebar
作为显示选项列表的组件,并接收回调函数作为其 props。回调函数将从Sidebar
调用通过单击其中一个按钮,您可以通知包含组件(父级)的单击:
class SomethingThatUsesSidebar extends Component {
onSidebarOptionSelect(option) {
console.log(option);
}
render() {
return (
<div>
<Sidebar onOptionSelect={this.onSidebarOptionSelect.bind(this)} />
</div>
);
}
}
在您的 Sidebar
中组件,您可以像这样调用回调函数:
class Sidebar extends Component {
// ...
_onOptionChange(option) {
this.props.onOptionSelect(option);
}
render() { ... }
}
关于javascript - react 与 Bootstrap : returning the value of selected radio button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42612035/