在react-js

时间:2017-02-25 05:40:41

标签: reactjs react-native react-jsx

output look like this当我点击更改文本按钮时,它应该用该值替换文本(TodoApplication),如果它是空值(应该替换空标题),则此代码中的值没有变化!任何人都可以编辑代码来获得解决方案!



var TodoApp = React.createClass({
  getInitialState: function() {
return {items: []};
  },
  updateItems: function(newItem) {
var allItems = this.state.items.concat([newItem]);
this.setState({items: allItems});
  },
  render: function() {
return (
  <div>
    <TodoBanner/>
    <TodoList items={this.state.items}/>

    <TodoForm onFormSubmit={this.updateItems}/>
  </div>
);
  }
});

var TodoBanner = React.createClass({
  render: function() {
return (
  <div className="container">
    <h3>TODO Application</h3>
  </div>
);
  }
});

var TodoList = React.createClass({
  render: function() {
var createItem = function(itemText) {
  return (
    <TodoListItem>{itemText}
    </TodoListItem>
  );
};
return <ul>{this.props.items.map(createItem)}</ul>;
  }
});

var TodoListItem = React.createClass({
  render: function() {
return (
  <li>{this.props.children}</li>
);
  }
});

var TodoForm = React.createClass({
  getInitialState: function() {
return {item: ''};
  },
  handleSubmit: function(e) {
e.preventDefault();
this.props.onFormSubmit(this.state.item);
this.setState({item: ''});
React.findDOMNode(this.refs.item).focus();
return;
  },
  onChange: function(e) {
this.setState({item: e.target.value});
  },
  render: function() {
return (
  <div className="container">
    <form onSubmit={this.handleSubmit}>
      <input type='text' ref='item' onChange={this.onChange} value={this.state.item}/>
      &nbsp;
      <input type='submit' value='Add' className="btn btn-success"/><br/>
      <input type='text' ref='item' onChange={this.onChange} value={this.state.item}/>
      &nbsp;
      <input type='submit' value='Change Text' className="btn btn-success"/>
    </form>
  </div>
);
  }
});

ReactDOM.render(
  <TodoApp/>, document.getElementById('todo'));       
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>

<div id="todo" />
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

恐怕我没听懂你的意思。你的意思是这样吗?

https://jsfiddle.net/alfrcr/upzqf067/1/

如果是这样,为了更改“Todo Application”文本,您应该将表单状态发送到上层组件。

因此TodoBanner可以将“形成状态”作为props进行访问。 (参见示例代码)