我是新手,想要根据react-starter-kit构建一个简单的ToDo应用程序.我正在使用ES6类,无法找到从子组件更新父状态的方法.
这是代码:
import React, { PropTypes, Component } from 'react';
import withStyles from '../../decorators/withStyles';
import styles from './ToDoPage.less';
@withStyles(styles)
class ToDoPage extends Component {
static contextTypes = {
onSetTitle: PropTypes.func.isRequired
};
constructor() {
super();
this.state = {
items: ['Item1', 'Item2'],
value: ''
};
}
updateValue(newValue) {
//this.state is null here
this.setState({
value: newValue
});
}
clickHandler() {
console.log('AddToDo state:', this.state)
if (this.state.value && this.state.items) { //this.state is null here
this.setState({
items: this.state.items.push(this.state.value)
});
}
}
render() {
let title = …Run Code Online (Sandbox Code Playgroud) 我在 react native 中有一个组件:
export default class Screen extends Component {
constructor(props){
super(props);
this.state = {
prop1: false,
prop2: simpleFunc
};
}
simpleFunc = () => { /*...*/ }
componentWillMount() {
BackgroundGeolocation.on('location', this.onLocation);
Run Code Online (Sandbox Code Playgroud)
最后一行是将在新位置调用的回调方法。
从该方法我无法访问this.state或this.simpleFunc().
我应该怎么做才能从回调函数更新状态?
我正在关注React Beginner Tutorial,我正在尝试将其翻译成ES6.然而,当我改变了CommentBox一个ES6类它开始给我一个this.props.url是undefined错误(在AJAX调用loadCommentsFromServer).我认为这与ES6如何绑定有关this,但是我对语言(也不是React)不太熟悉,所以我不确定.我查看了React 0.13发行说明并看到了这个:
React.createClass具有内置的魔术功能,可以
this自动为您绑定所有方法.对于那些在其他类中不习惯此功能的JavaScript开发人员来说,这可能会有点混乱,或者当他们从React迁移到其他类时会让人感到困惑.
我不完全确定,但我认为这意味着我必须保存它的价值(如在let that = this和中.bind(that)),但同样this.props.url也是undefined- 我不知道下一步该去哪里.
这是我目前的代码:
class CommentBox extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
loadCommentsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({
data: data
})
}.bind(this)
});
}
handleCommentSubmit(comment) {
var comments = this.state.data;
var newComments = comments.concat([comment]);
this.setState({ …Run Code Online (Sandbox Code Playgroud) 我刚接触使用react并遇到了问题:
未捕获的TypeError:无法读取null的属性"setState".
基本上我要做的是,用户可以点击三个不同的标题,点击后,它将呈现特定于该标题的特定模板.这是我正在使用的代码,它给了我这个错误:
class Selection extends React.Component {
constructor(props) {
super(props);
this.state = {selections: [], donateActive: true, fundraiseActive: false, speakActive: false };
}
componentDidMount() {
this.setState({
selections: selectionData.selections
})
}
componentWillUnMount(){
console.log("unmounted!");
}
donateOnClick() {
this.setState({ donateActive: true, fundraiseActive: false, speakActive: false});
}
fundraiseOnClick() {
this.setState({ fundraiseActive: true, donateActive: false, speakActive: false});
}
speakOnClick() {
this.setState({ speakActive: true, fundraiseActive: false, donateActive: false});
}
donateTemplate() {
return (
<div>
<h1>donate template</h1>
</div>
)
}
fundraiseTemplate() {
return (
<div>
<h1>fundraise template</h1> …Run Code Online (Sandbox Code Playgroud) 通常,当我单击子组件中的菜单项时,它会调用 {this.handlesort},这是一个本地函数。处理排序从我的父组件接收 onReorder 道具。{onReorder} 调用名为 reOrder 的本地函数。它设置 {orderBy 和 orderDir} 的状态。问题是,当我单击 {menuitem} 时,它立即返回此错误。(未捕获的类型错误:无法读取未定义的属性“onReOrder”)。通常它在我不使用 es6 时工作。请帮忙
(父组件)
export default class TenantView extends Component {
constructor(props) {
super(props);
//setting state
this.state = {
//tenants: [],
orderBy: 'name',
orderDir: 'asc',};
};
componentWillMount() {
this.setState({
tenants:[{img: 'tenant1.jpg',name: 'John', address: '7 Gilbert',
paid: 'true'},{img: 'tenant2.jpg',name:'Abba', address:
'3 Vecq st', }]});//setState
}//componentWillMount
reOrder(orderBy, orderDir) {
this.setState({
orderBy: orderBy,
orderDir: orderDir,
});//setState
}//reorder
render(){
var tenants = this.state.tenants;
var orderBy = this.state.orderBy;
var orderDir = this.state.orderDir;
tenants …Run Code Online (Sandbox Code Playgroud) 我是新手React js,我不知道下面的代码有什么问题,但我得到的setState不是函数错误.请帮我解决这个问题.
class AppBarLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
visibleSideBar:true,
slide:""
}
}
showProfile(){
this.setState({
slide:'slide'
});
console.log(this.state.slide);
}
render(){
return(
<div>
<header>
<NavBar show={this.showProfile}/>
<Profile slide={this.state.slide} />
</header>
</div>
);
}
}
export default AppBarLayout;
Run Code Online (Sandbox Code Playgroud) 使用ReactJS的es6方法与类中的方法中的'this'关键字的上下文混淆
这给出了一个错误,无法获得未定义的引用
class AddItem extends React.Component {
constructor() {
super();
}
addIt(e) {
e.preventDefault();
let newItem = {
title: this.refs.title.value
}
this.refs.feedForm.reset();
this.props.addItem(newItem);
}
render() {
return (
<div>
<form ref="feedForm" onSubmit={this.addIt}>
<div className="input-group">
<span className="input-group-addon"><strong>Title:</strong></span>
<input ref="title" type="text" className="form-control" />
</div>
<button className="btn btn-success btn-block">Add Item</button>
</form>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
但这似乎工作正常
class AddItem extends React.Component {
constructor() {
super();
this.addIt = function(e) {
e.preventDefault();
let newItem = {
title: this.refs.title.value
}
this.refs.feedForm.reset();
this.props.addItem(newItem);
}.bind(this)
}
render() {
return …Run Code Online (Sandbox Code Playgroud) 我只是尝试一些简单的东西,比如只在handleSubmit函数中打印this.state.validForm,但我似乎无法访问this.state.validForm.首先我直接尝试使用此功能,但无济于事.我是新来的反应.
import React, { Component } from 'react';
import TextInput from './TextInput';
class RequestForm extends Component {
constructor(props) {
super(props);
this.state = {validForm : "false"};
this.getInfoForm = this.getInfoForm.bind(this);
}
getInfoForm() {
return this.state.validForm;
}
handleSubmit(event) {
event.preventDefault();
console.log('submit values are');
console.log(event.target.src.value);
console.log(event.target.email.value);
console.log(this.state.validForm);
console.log(this.getInfoForm());
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<TextInput
uniqueName="email"
name="email"
text="Email Address"
required={true}
minCharacters={6}
validate="email"
errorMessage="Email is invalid"
emptyMessage="Email is required"
/>
<TextInput
text="User"
name="User src"
required={true}
minCharacters={3}
validate="notEmpty"
errorMessage="Name is invalid"
emptyMessage="Name is required"
/> …Run Code Online (Sandbox Code Playgroud) 使用ES6类语法,我无法保留context类中其他方法的值.例如:
class Repos extends React.Component {
constructor(props, context) { // eslint-disable-line
super(props, context);
console.log(this.context.router);
}
handleSubmit(event) {
event.preventDefault();
const userName = event.target.elements[0].value;
const repo = event.target.elements[1].value;
const path = `/repos/${userName}/${repo}`;
console.log(path); // eslint-disable-line
this.context.router.push(path);
}
Run Code Online (Sandbox Code Playgroud)
对于第一个控制台日志,上下文仍然存在:
对于第二个控制台日志,不是那么多:
如何this.context在构造函数之外的方法中处理,但在类中?
我重构了一个从ES5到ES6的React类,现在当我点击一个调用按钮时,行开头this.state.dispatch(logIn(this.state.logIn))的初始this值为null.超级怪异.
这是我的班级:
class Home extends Component {
constructor(props) {
super(props);
this.state = {
panelIsOpen: false,
registration: {},
login: {},
};
}
signUp() {
this.props.dispatch(signUp(this.state.registration));
this.setState({
registration: {},
});
}
logIn() {
debugger; // this is `null here`
this.props.dispatch(logIn(this.state.login));
this.setState({
login: {},
});
}
togglePanel(e) {
this.setState({ panelIsOpen: !this.state.panelIsOpen} );
}
render() {
const {elements} = this.props;
const {registration, login} = this.state;
return (
// some stuff
);
}
};
Home.propTypes = {
elements: React.PropTypes.array,
dispatch: React.PropTypes.func, …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
export default class Contact extends React.Component {
constructor(props) {
super(props);
this.state = {
password: '',
redirect: false,
username: ''
};
this.onUsernameChange = this.onUsernameChange.bind(this);
this.onPasswordChange = this.onPasswordChange.bind(this);
}
onUsernameChange(event) {
this.setState({ username: event.target.value });
}
onPasswordChange(event) {
this.setState({ password: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
alert('A name was submitted: ' + this.state.username);
//sessionStorage.setItem('username', this.state.username);
}
render() {
return (
<div>
<form className="form-signin" onSubmit={this.handleSubmit}>
<input type="text" value={this.username} onChange={this.onUsernameChange} />
<input type="password" value={this.password} onChange={this.onPasswordChange} />
<input type="submit" value="Submit" />
</form>
</div>
); …Run Code Online (Sandbox Code Playgroud) reactjs ×11
javascript ×7
ecmascript-6 ×6
class ×1
gatsby ×1
meteor ×1
react-jsx ×1
react-native ×1
react-redux ×1
this ×1