我在两个组件中有两个TextField。当一个TextField改变值时,我如何才能发送和更改TextField的剩余值?
这是我的问题的例子。这是我的问题。我有url http://localhost:8000/search?search=php&category=catqgkv4q01ck7453ualdn3sd&page=1搜索页面Js:
class SearchPage extends Component {
constructor(props) {
super(props);
let search = typeof this.props.location.query.search !== '' ? this.props.location.query.search : '';
if(search){
this.props.dispatch(setTextSearch(search));
}
};
render() {
return (
<MuiThemeProvider>
<div id='search-page'>
<SearchTextBox textSearch={this.props.textSearch}/>
</div>
</MuiThemeProvider>
)
}
}
// Retrieve data from store as props
function mapStateToProps(state) {
return {
textSearch: getTextSearch(state)
}
}
SearchPage.contextTypes = {
router: React.PropTypes.object
};
export default connect(mapStateToProps)(SearchPage);搜索行动:
import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
SET_TEXT_SEARCH: 'SET_TEXT_SEARCH'
};
export function setTextSearch(search) {
return {
type: ACTIONS.SET_TEXT_SEARCH,
search
};
}搜索减速机:
import { ACTIONS } from './SeachActions';
// Initial State
const initialState = {
textSearch: '',
};
const SearchReducer = (state = initialState, action) => {
switch (action.type) {
case ACTIONS.SET_TEXT_SEARCH:
state.textSearch = action.search;
return {...state};
default:
return state;
}
};
/* Selectors */
export const getTextSearch = state => state.categories.textSearch;
// Export Reducer
export default SearchReducer;我有组件SearchTextBox
import React from 'react';
import TextField from 'material-ui/TextField';
export default class SearchTextBox extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.textSearch,
};
};
render() {
return (
<TextField
hintText="Search"
className="search-txtbox"
ref='searchText'
style={{height : '40'}}
underlineShow={false}
value={this.state.value}
onChange={this.handleChange}
autoFocus
onKeyPress={this.handleEnter}
/>
);
}
}如何通过上的数据参数“搜索”更改值
发布于 2016-12-10 13:20:49
因此,您的问题似乎是如何与其他组件共享相同的数据(将某种数据相互传递,而不仅仅是状态,可能是任何事情)。
您应该知道组件之间通信数据的可用方式。
1-道具
2-背景
3-全局变量(反模式,直到您真正需要时,当您需要时,应该使用redux或类似的工具和上下文创建一个大的全局数据树,而不需要创建全局变量)。
因此,没有其他方法在组件之间进行数据通信。
然后,由于我们知道可用的选项,第二个问题是,我想要的组件是如何在相对于彼此的位置之间通信数据。
一个是另一个的亲生父母。
一个是另一个的间接父母。
3-双方都有相同的父母。
假设您的TextFields共享相同的父级,幸运的是,这里有一个工作代码供您理解。
const TextField = ({
value = '', handleInputChange = ''
}) => <input type="text" value={value} onChange={ handleInputChange }/>
class ParentC extends React.Component {
state = {
sharedInputValue : ''
}
constructor(props){
super(props)
this.state = {
sharedInputValue : ''
}
this.handleInputChange = this.handleInputChange.bind(this)
}
handleInputChange( event ){
this.setState({ sharedInputValue : event.target.value})
}
render(){
return (
<div>
<TextField
value={ this.state.sharedInputValue }
handleInputChange={ this.handleInputChange }
/>
<TextField
value={ this.state.sharedInputValue }
handleInputChange={ this.handleInputChange }
/>
</div>
)
}
}https://stackoverflow.com/questions/41075076
复制相似问题