如何有条件地在文本上附加b标签?

时间:2017-06-19 08:32:26

标签: javascript html reactjs

我有这个代码用于分页和搜索:

return this.props.todos.filter( (todo) => todo.text.toLowerCase().indexOf(this.state.searchText.toLowerCase()) !== -1 ).slice( (currentPage - 1) * pageSize, currentPage * pageSize ).map((todo,todoIndex) => {
          return <Todo
            key={todo.id}
            {...todo} // pass all the todo property
            onClick={() => onTodoClick(todo.id)}
            onTrashClick={() => onDeleteClick(todo.id, todoIndex)}
            handleSelectedTodo = {this._handleSelectedTodo}
            isChecked={this.state.checkedIds.includes(todo.id)}
          />

在Todo组件上,我正在考虑在与searchText状态匹配的文本中推送 标记。像这样:

todo.text.indexOf(this.state.searchText) ? todo.text.split(').push('<b>.....

因此,如果文本的某些部分与searchText状态匹配,我将推送标记,以便在this.state.searchText = 'cde'text = 'abcdefg'时结果如下:

'a<b>cde</b>fg'

帮助?

1 个答案:

答案 0 :(得分:1)

也许是这样的?

&#13;
&#13;
function callmyfunction(item, cb) {
    // do uploading...
    // execute cb after upload
    cb();
}

function drop(e){
    e.stopPropagation();
    e.preventDefault();
    //call start modal (waiting file uploading...)
    var items = e.dataTransfer.items;
    for(var i=0; i<items.length; i++){
        var item = items[i].webkitGetAsEntry();
        if (item){
            callmyfunction(item, function() { 
              // close modal
            });
        }
    }
}
&#13;
const Todo = ({ rSearch, text }) => {
  var strs = text.split(rSearch);
  return (
    <span>
      {strs.map(
        (str, i) =>
          rSearch.test(str) ? <b key={i}>{str}</b> : <span key={i}>{str}</span>
      )}
    </span>
  );
};

class TodoList extends React.Component {
  state = {
    searchText: 'cde'
  };
  render() {
    const { items } = this.props;
    const { searchText } = this.state;
    const rSearch = new RegExp(`(${searchText})`, 'g');
    return (
      <div>
        <input type="text" defaultValue={searchText} />
        <ul>
          {items.map((item, i) =>
            <li key={i}>
              <Todo rSearch={rSearch} text={item.text} />
            </li>
          )}
        </ul>
      </div>
    );
  }
}

const todoItems = [
  {
    text: 'abcdefgh'
  },
  {
    text: 'ijkcdefgh'
  }
];

ReactDOM.render(
  <TodoList items={todoItems} />,
  document.getElementById('root')
);
&#13;
&#13;
&#13;